Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/1ba09a058cb6f1eefd35 to your computer and use it in GitHub Desktop.
Save markhowellsmead/1ba09a058cb6f1eefd35 to your computer and use it in GitHub Desktop.
Measure how fast an image loads: mainly to test network speed
/*
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