Skip to content

Instantly share code, notes, and snippets.

@celsobessa
Forked from debloper/bandwidth.js
Last active June 25, 2021 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsobessa/16598aa960d40db64af16f02d1ff9052 to your computer and use it in GitHub Desktop.
Save celsobessa/16598aa960d40db64af16f02d1ff9052 to your computer and use it in GitHub Desktop.
Determine client's connection speed with JavaScript
// Let's initialize the primitives
var startTime, endTime, fileSize, result, unit = {kbps:1,kBps:8};
// Set up the AJAX to perform
var xhr = new XMLHttpRequest();
// Rig the call-back... THE important part
xhr.onreadystatechange = function () {
// we only need to know when the request has completed
if (xhr.readyState === 4 && xhr.status === 200) {
// Here we stop the timer & register end time
endTime = (new Date()).getTime();
// Also, calculate the file-size which has transferred
fileSize = xhr.responseText.length;
// N.B: fileSize reports number of Bytes
// Calculate the connection-speed
var speed = fileSize / ((endTime - startTime)/1000) / 1024;
// Use (fileSize * 8) instead of fileSize for kBps instead of kbps
// Report the result, or have fries with it...
console.log(speed + " kbps\n");
}
}
// Snap back; here's where we start the timer
startTime = (new Date()).getTime();
// All set, let's hit it!
xhr.open("GET", "URL/TO/PROBE.FILE", true);
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment