How to detect internet speed in JavaScript?

前端 未结 9 1499
萌比男神i
萌比男神i 2020-11-22 01:56

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”.

9条回答
  •  攒了一身酷
    2020-11-22 02:39

    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:

    • https://github.com/collective/experimental.bwtools/blob/master/src/experimental/bwtools/browser/static/scripts/

提交回复
热议问题