Last active
August 29, 2015 14:25
-
-
Save markhowellsmead/1ba09a058cb6f1eefd35 to your computer and use it in GitHub Desktop.
Measure how fast an image loads: mainly to test network speed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This example is the basis of a simple WordPress plugin | |
which measures the download speed of a sample image | |
and then sends this information to the server for further action. | |
(e.g. writing to a database) | |
*/ | |
function measureSpeed() { | |
var duration = (endTime - startTime) / 1000; | |
var bitsLoaded = downloadSize * 8; | |
var speedBps = Math.round(bitsLoaded / duration); | |
try{ | |
// add your functionality to define what you want to do with the | |
// ajax response. e.g. set a cookie or whatever | |
}catch(e){} | |
} | |
var startTime = (new Date()).getTime(), | |
endTime, | |
imageAddr = 'assets/speed.png?n=' + Math.random(), // change to match the path of the sample image | |
downloadSize = 1441, // file size of the sample image in bytes | |
download = new Image(); | |
download.src = imageAddr; | |
download.onload = function () { | |
endTime = (new Date()).getTime(); | |
measureSpeed(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment