Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Determine client's connection speed with JavaScript
// Let's initialize the primitives
var startTime, endTime, fileSize;
// 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;
// Calculate the connection-speed
var speed = (fileSize * 8) / ((endTime - startTime)/1000) / 1024;
// 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();
@YashKharel19

This comment has been minimized.

Copy link

YashKharel19 commented May 3, 2018

what does xhr.open("GET", "URL/TO/PROBE.FILE", true); do ? what is URL/TO/PROBE.FILE

@npgenx

This comment has been minimized.

Copy link

npgenx commented May 11, 2018

@YashKharel19 <URL/TO/PROBE.FILE> you replace that with file on your server e.g. http://mydomain.tld/foo.img. This script basically check how long the file took to download to the client's browser

@Sinstrite

This comment has been minimized.

Copy link

Sinstrite commented Feb 16, 2019

What are you calculating the connection speed in, Kibibits, Kilobits, etc?

A bit confused by the formula.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.