When we try to use JavaScipt measured network speed

npm packet address

Github Address

 
The way it is, try to write a recent judgment by the current network speed, thus the request to the control of the front step of requesting a large file libraries. The stuff I have not written a line of code, in addition to this demand suddenly found the idea somewhat less than the actual, the other reason is that I suddenly asked myself -
Nima front-end speed to determine how ah? ??!
 

Principle front-end speed judgment summary

(Note: The following default unit is seeking speeds KB / S )
Through access to relevant information, I found that the main idea is divided into the following categories:
 

1. img loading or initiate requesting computing network speed Ajax

And by requesting a file server with the domain, such as pictures, etc., at a front end and start request received a response time of two points are marked by start and End Date.now, because Date.now derived January 1, 1970 day (UTC) to the current number of milliseconds elapsed time, so we by end - start to obtain the time difference (ms), and then by calculating:
File Size (KB) * 1000 / (end -start)

It can be calculated the speed (KB / S).

The request file there are two ways: by AJAX img load or load:
  • By creating img object, setting the onload callback listener, and then specify the src, once designated src, picture resources will be loaded, onload callback is invoked when done, we can mark the start and end, respectively, according to the timing.
  • Request by AJAX, for XHR object created in onreadystatechange callback, the time is determined when the loaded readystate = 4, were labeled according to the start and end timing.

2.window.navigator.connection.downlink speed query

We can also go to some of the H5 achieved through advanced API, for example, where we can use the window.navigator.connection.downlink to query, but as you know is that the API is a virtue that is commonplace compatibility issues , so we are generally prepared as a means, through the ability to detect, can use it, it can not be used by other methods. Note downlink and the unit is mbps, converted to the formula KB / S is
navigator.connection.downlink * 1024 / 8

Take 1024 can understand why the back to 8 except it? This is because in the mbps b refers to the 'bit (bits), KB / s refers to the inside Byte B (byte), 1 byte (b) = 8 bits (' bit) , it is necessary in addition to 8
 

3. In general, network speed is estimated by requesting the file, there may be a single error, so we can request several times and calculate the average.

 

The method of determining speed of the front end of their advantages and disadvantages

  • img load speed : With the img object to load calculation network speed. Advantages: no problem with cross-domain brings. Disadvantages: (1) to measure their own file size and provide parameters fileSize, (2) file must be an image (3) File size can not flexibly control
  • Ajax speed : Ajax estimates by network speed. Advantages: (1) do not provide the file size parameters, because you can get (2) test file from the header of response does not have to picture, and the amount of data can be flexibly controlled. Disadvantages: cross-domain issues
  • speed downlink : network speed read by navigator.connection.downlink. Advantages: does not require any parameters. Disadvantages: 1 compatibility is very problematic, 2 Bandwidth query is not real-time, with a minute time interval level
  • Comprehensive realization : first try using downlink speed, otherwise AJAX gun several times and averaged

img loaded gun

function getSpeedWithImg(imgUrl, fileSize) {
    return new Promise((resolve, reject) => {
        let start = null;
        let end = null;
        let img = document.createElement('img');
        start = new Date().getTime();
        img.onload = function (e) {
            end = new Date().getTime();
            const speed = fileSize * 1000 / (end - start)
            resolve(speed);
        }
        img.src = imgUrl;
    }).catch(err => { throw err });
}

 

Ajax gun

function getSpeedWithAjax(url) {
    return new Promise((resolve, reject) => {
        let start = null;
        let end = null;
        start = new Date().getTime();
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                end = new Date().getTime();
                const size = xhr.getResponseHeader('Content-Length') / 1024;
                const speed = size * 1000 / (end - start)
                resolve(speed);
            }
        }
        xhr.open('GET', url);
        xhr.send();
    }).catch(err => { throw err });
}

 

downlink speed

function getSpeedWithDnlink() {
    // downlink测算网速
    const connection = window.navigator.connection;
    if (connection && connection.downlink) {
        return connection.downlink * 1024 / 8;
    }
}

 

Integrated speed

function getNetSpeed(url, times) {
    // downlink测算网速
    const connection = window.navigator.connection;
    if (connection && connection.downlink) {
        return connection.downlink * 1024 / 8;
    }
    // 多次测速求平均值
    const arr = [];
    for (let i = 0; i < times; i++) {
        arr.push(getSpeedWithAjax(url));
    }
    return Promise.all(arr).then(speeds => {
        let sum = 0;
        speeds.forEach(speed => {
            sum += speed;
        });
        return sum / times;
    })
}

 

 
The above code I made a npm package, available for download
npm i network-speed-test

Use

import * from 'network-speed-test';
getSpeedWithImg("https://s2.ax1x.com/2019/08/13/mPJ2iq.jpg", 8.97).then(
    speed => {
        console.log(speed);
    }
)

getSpeedWithAjax('./speed.jpg').then(speed => {
    console.log(speed);
});

getNetSpeed('./speed.jpg', 3).then(speed => {
    console.log(speed);
});

getSpeedWithDnlink();

 

Github Address

 

Reference article

https://juejin.im/post/5b4de6b7e51d45190d55340b

 

 

Know almost Account

 
 

Guess you like

Origin www.cnblogs.com/penghuwan/p/11366446.html