Search code examples
javascriptbandwidthcontent-delivery-network

Checking someones bandwidth and loading content based on it


I have seen a number of questions that don't answer this, is it possible to check someones bandwidth using java script and load specific content based on it?

The BBC seem to give me low quality images when using my mobile and in the middle of nowhere.

by the looks of this this cool service does this and its a CDN so it could be server side.

http://www.resrc.it/docs/

Does anyone know how they do it? or how I could do it using asp.net or javascript, or an community opensource plug in.

I think it may be possible with https://github.com/yahoo/boomerang/ but not sure this is its true purpose.


Solution

  • Basically you do this like this:

    • Start a timer
    • Load an fixed size file e.g a image through an ajax call
    • Stop the timer
    • Take some samples and compute the average badwidth

    Somethign like this could work:

    //http://upload.wikimedia.org/wikipedia/commons/5/51/Google.png
    //Size = 238 KB
    function measureBW(cnt, cb) {
        var start = new Date().getTime();
        var bandwidth;
        var i = 0;
        (function rec() {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open('GET', 'http://upload.wikimedia.org/wikipedia/commons/5/51/Google.png', true);
    
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    var x = new Date().getTime() - start;
                    bw = Number(((238 / (x / 1000))));
                    bandwidth = ((bandwidth || bw) + bw) / 2;
                    i++;
                  if (i < cnt) {
                    start = new Date().getTime();rec();
                  }
                    else cb(bandwidth.toFixed(0));
                }
            };
            xmlHttp.send(null);
        })();
    
    }
    
    measureBW(10, function (e) {
        console.log(e);
    });
    

    Not that var xmlHttp = new XMLHttpRequest(); won't work on all browsers, you should check for the UserAgent and use the right one

    And of course its just an estimated value.

    Heres a JSBin example