Recently, there is a need to detect the bandwidth of the network in the project. We have found many solutions on the Internet. Wang er will do the following sorting

1. Method 1

The first idea is to load an image and calculate the network bandwidth by the loading time and the size of the image

With this in mind, we can look at the following code (partly from debloper/bandwidth.js on Github) :

function measureBW(fn) {
    var startTime, endTime, fileSize;

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = (a)= > {
        if(xhr.readyState === 2){
            startTime = Date.now();
        }
        if (xhr.readyState === 4 && xhr.status === 200) {
            endTime = Date.now();
            fileSize = xhr.responseText.length;
            var speed = fileSize  / ((endTime - startTime)/1000) / 1024;
            fn && fn(Math.floor(speed))
        }
    }

    xhr.open("GET"."https://upload.wikimedia.org/wikipedia/commons/5/51/Google.png".true);
    xhr.send();
}

measureBW((speed) = >{
    console.log(speed + " KB/sec");  //215 KB/sec
})
Copy the code

2. Method two

However, considering that HTTP requests require establishing a connection and waiting for a response, these processes can also take some time, so the above method may not accurately detect network bandwidth.

We can make multiple requests at the same time to reduce the impact of the HTTP request establishing a connection and waiting for a response, as shown in the following code:

function measureBW(fn,time) {
    time = time || 1;
    var startTime, endTime, fileSize;
    var count = time ;
    var _this = this;
    function measureBWSimple () {
        
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = (a)= > {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if(! fileSize){ fileSize = xhr.responseText.length; } count --;if(count<=0){
                    endTime = Date.now();
                    var speed = fileSize * time  / ((endTime - startTime)/1000) / 1024;
                    fn && fn(Math.floor(speed));
                }
            }
        }
        xhr.open("GET"."https://upload.wikimedia.org/wikipedia/commons/5/51/Google.png".true);
        xhr.send();
    }
    startTime = Date.now();
    for(varx = time; x>0; x--){ measureBWSimple() } } measureBW((speed) = >{
    console.log(speed + " KB/sec");  //913 KB/sec
},10)
Copy the code

By wang ii test, the second method to get the results of the method one results significantly higher than many.

In fact, the first two require additional HTTP headers to disable the use of local caching (you can disable caching by clicking on the console Network panel during development testing), otherwise the image will not be loaded to the server after loading once, and the Network bandwidth will not be determined.

3. Method three

In Chrome65+, native methods have been added to detect information about the connection the device is using to communicate with the network.

We can detect the network bandwidth by referring to the following code:

function measureBW () {
    return navigator.connection.downlink;
}
measureBW() ;
Copy the code

The navigator. The connection. The downlink will be returned to (megabit per second) as the unit of the effective bandwidth estimation (MDN) reference, this and our commonly used (KB/SEC) is different, so we need to do the unit conversion, refer to the following code:

function measureBW () {
    return navigator.connection.downlink * 1024 /8;   // The unit is KB/ SEC
}
measureBW() ;
Copy the code

We can also listen for changes in network bandwidth via the change event on navigator.connection:

navigator.connection.addEventListener('change', measureBW());
Copy the code

Reference article:

MDN NetworkInformation

Network Information API Sample

Kbps, KB, Mbps unit conversion

Original address:

Wang Yulue’s personal website