[javascript] How to detect internet speed in JavaScript?

How can I create a JavaScript page that will detect the user’s internet speed and show it on the page? Something like “your internet speed is ??/?? Kb/s”.

This question is related to javascript download-speed

The answer is


I needed something similar, so I wrote https://github.com/beradrian/jsbandwidth. This is a rewrite of https://code.google.com/p/jsbandwidth/.

The idea is to make two calls through Ajax, one to download and the other to upload through POST.

It should work with both jQuery.ajax or Angular $http.


The image trick is cool but in my tests it was loading before some ajax calls I wanted to be complete.

The proper solution in 2017 is to use a worker (http://caniuse.com/#feat=webworkers).

The worker will look like:

/**
 * This function performs a synchronous request
 * and returns an object contain informations about the download
 * time and size
 */
function measure(filename) {
  var xhr = new XMLHttpRequest();
  var measure = {};
  xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
  measure.start = (new Date()).getTime();
  xhr.send(null);
  measure.end = (new Date()).getTime();
  measure.len = parseInt(xhr.getResponseHeader('Content-Length') || 0);
  measure.delta = measure.end - measure.start;
  return measure;
}

/**
 * Requires that we pass a base url to the worker
 * The worker will measure the download time needed to get
 * a ~0KB and a 100KB.
 * It will return a string that serializes this informations as
 * pipe separated values
 */
onmessage = function(e) {
  measure0 = measure(e.data.base_url + '/test/0.bz2');
  measure100 = measure(e.data.base_url + '/test/100K.bz2');
  postMessage(
    measure0.delta + '|' +
    measure0.len + '|' +
    measure100.delta + '|' +
    measure100.len
  );
};

The js file that will invoke the Worker:

var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
  return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
  base_url: base_url
});
w.onmessage = function(event) {
  if (event.data) {
    set_cookie(event.data);
  }
};

Code taken from a Plone package I wrote:


thanks to Punit S answer, for detecting dynamic connection speed change, you can use the following code :

navigator.connection.onchange = function () {
 //do what you need to do ,on speed change event
 console.log('Connection Speed Changed');
}

As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.

That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.


It's better to use images for testing the speed. But if you have to deal with zip files, the below code works.

var fileURL = "your/url/here/testfile.zip";

var request = new XMLHttpRequest();
var avoidCache = "?avoidcache=" + (new Date()).getTime();;
request.open('GET', fileURL + avoidCache, true);
request.responseType = "application/zip";
var startTime = (new Date()).getTime();
var endTime = startTime;
request.onreadystatechange = function () {
    if (request.readyState == 2)
    {
        //ready state 2 is when the request is sent
        startTime = (new Date().getTime());
    }
    if (request.readyState == 4)
    {
        endTime = (new Date()).getTime();
        var downloadSize = request.responseText.length;
        var time = (endTime - startTime) / 1000;
        var sizeInBits = downloadSize * 8;
        var speed = ((sizeInBits / time) / (1024 * 1024)).toFixed(2);
        console.log(downloadSize, time, speed);
    }
}

request.send();

This will not work very well with files < 10MB. You will have to run aggregated results on multiple download attempts.


Mini snippet:

var speedtest = {};
function speedTest_start(name) { speedtest[name]= +new Date(); }
function speedTest_stop(name) { return +new Date() - speedtest[name] + (delete 
speedtest[name]?0:0); }

use like:

speedTest_start("test1");

// ... some code

speedTest_stop("test1");
// returns the time duration in ms

Also more tests possible:

speedTest_start("whole");

// ... some code

speedTest_start("part");

// ... some code

speedTest_stop("part");
// returns the time duration in ms of "part"

// ... some code

speedTest_stop("whole");
// returns the time duration in ms of "whole"

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail


I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clearly distinguish between 3G or Wi-Fi for example, maybe someone can make a more elegant version or even a jQuery plugin.

_x000D_
_x000D_
var arrTimes = [];_x000D_
var i = 0; // start_x000D_
var timesToTest = 5;_x000D_
var tThreshold = 150; //ms_x000D_
var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server_x000D_
var dummyImage = new Image();_x000D_
var isConnectedFast = false;_x000D_
_x000D_
testLatency(function(avg){_x000D_
  isConnectedFast = (avg <= tThreshold);_x000D_
  /** output */_x000D_
  document.body.appendChild(_x000D_
    document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)_x000D_
  );_x000D_
});_x000D_
_x000D_
/** test and average time took to download image from server, called recursively timesToTest times */_x000D_
function testLatency(cb) {_x000D_
  var tStart = new Date().getTime();_x000D_
  if (i<timesToTest-1) {_x000D_
    dummyImage.src = testImage + '?t=' + tStart;_x000D_
    dummyImage.onload = function() {_x000D_
      var tEnd = new Date().getTime();_x000D_
      var tTimeTook = tEnd-tStart;_x000D_
      arrTimes[i] = tTimeTook;_x000D_
      testLatency(cb);_x000D_
      i++;_x000D_
    };_x000D_
  } else {_x000D_
    /** calculate average of array items then callback */_x000D_
    var sum = arrTimes.reduce(function(a, b) { return a + b; });_x000D_
    var avg = sum / arrTimes.length;_x000D_
    cb(avg);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_


Even though this is old and answered, i´d like to share the solution i made out of it 2020

it comes with the flexibility to run at anytime and run a callback if greater and or smaller the specified mbps

you can start the test anywhere after you included the testConnectionSpeed Object by running the testConnectionSpeed.run(mbps, morefunction, lessfunction)

for example:

_x000D_
_x000D_
var testConnectionSpeed = {
  imageAddr : "https://upload.wikimedia.org/wikipedia/commons/a/a6/Brandenburger_Tor_abends.jpg", // this is just an example, you rather want an image hosted on your server
  downloadSize : 2707459, // this must match with the image above
  run:function(mbps_max,cb_gt,cb_lt){
    testConnectionSpeed.mbps_max = parseFloat(mbps_max) ? parseFloat(mbps_max) : 0;
    testConnectionSpeed.cb_gt = cb_gt;
    testConnectionSpeed.cb_lt = cb_lt;
    testConnectionSpeed.InitiateSpeedDetection();
  },
  InitiateSpeedDetection: function() {
    window.setTimeout(testConnectionSpeed.MeasureConnectionSpeed, 1);
  },
  result:function(){
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = testConnectionSpeed.downloadSize * 8;
    var speedBps = (bitsLoaded / duration).toFixed(2);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    if(speedMbps >= (testConnectionSpeed.max_mbps ? testConnectionSpeed.max_mbps : 1) ){
      testConnectionSpeed.cb_gt ? testConnectionSpeed.cb_gt(speedMbps) : false;
    }else {
      testConnectionSpeed.cb_lt ? testConnectionSpeed.cb_lt(speedMbps) : false;
    }
  },
  MeasureConnectionSpeed:function() {
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        testConnectionSpeed.result();
    }
    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = testConnectionSpeed.imageAddr + cacheBuster;
  }
}




// start test immediatly, you could also call this on any event or whenever you want
testConnectionSpeed.run(1.5, function(mbps){console.log(">= 1.5Mbps ("+mbps+"Mbps)")}, function(mbps){console.log("< 1.5Mbps("+mbps+"Mbps)")} )
_x000D_
_x000D_
_x000D_

I used this successfuly to load lowres media for slow internet connections. You have to play around a bit because on the one hand, the larger the image, the more reasonable the test, on the other hand the test will take way much longer for slow connection and in my case I especially did not want slow connection users to load lots of MBs.