js determines the user's current network status and determines the network speed


Recommended website for essential front-end tools (free picture bed, API, ChatAI and other practical tools):
http://luckycola.com.cn/


1. The first is to detect the network through the navigator provided by HTML5.

(1), Principle introduction:

Through the window.navigator.onLine property, a Boolean value is returned. true means online, false means offline. The onLine attribute can only simply determine the disconnection and connection status of the network, but cannot monitor network status changes, such as from 4g to 3g.

     if (window.navigator.onLine) {
    
    
       console.log('网络正常!');
     } else {
    
    
          console.log('网络中断!');
     }

(2) Compatibility

Insert image description here

2. Monitor window.ononline and window.onoffline events:

<script type="text/javascript">
    window.addEventListener("offline",function(){
    
    alert("网络连接恢复");})
    window.addEventListener("online",function(){
    
    alert("网络连接中断");})
</script>`

或者这样写

<script type="text/javascript">
    window.ononline=function(){
    
    alert("网络连接恢复");}
    window.onoffline=function(){
    
    alert("网络连接中断");}
</script>

3. Request judgment through ajax (good compatibility - recommended)

(1), Principle introduction:

The principle of this method is to calculate the current network speed through ajax request for a smaller resource and the resource return time, so the compatibility is better, and the specific network speed value can also be obtained, which is a better solution. plan

(2). Note:

However, one thing to note about this solution is that the image resources used for speed measurement must be small (more than a dozen K is enough), because if they are too large, the speed measurement will take too long and cause business congestion.

/ 判断网速 kb
export function measureBW(): Promise<number> {
    
    
    return new Promise((resolve, reject) => {
    
    
        let startTime = 0;
        let endTime = 0;
        let fileSize = 0;
        let xhr = new XMLHttpRequest();
        let measureTimerStatus = false;
        let measureTimer = setTimeout(() => {
    
    
            if (!measureTimerStatus) {
    
    
                resolve(50);
            };
        }, 5000);
        xhr.onreadystatechange = () =>{
    
    
            if(xhr.readyState === 2){
    
    
                startTime = Date.now();
            }
            if (xhr.readyState === 4 && xhr.status === 200) {
    
    
                endTime = Date.now();
                fileSize = xhr.responseText.length;
                // console.log(fileSize);
                let speed = fileSize  / ((endTime - startTime) / 1000) / 1024;
                // console.log('measureBW res:', speed);
                measureTimerStatus = true;
                measureTimer && clearTimeout(measureTimer);
                resolve(Math.floor(speed));
            }
        }
        xhr.open("GET", "https://www.google.com.hk/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png?id=" + Math.random(), true);
        xhr.send();
        xhr.onerror = () => {
    
    
            measureTimer && clearTimeout(measureTimer);
            measureTimerStatus = true;
            resolve(50)
        }
    });
}

4. Navigator.connection method monitors network changes

(1), Principle introduction:

It can monitor specific network changes (for example, changing from 4g to 3g), but it cannot monitor whether it is offline or online.

Insert image description here

const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

connection.addEventListener('change', () => {
    
    
    // connection.effectiveType返回的是具体的网络状态:4g/3g/2g
    console.log(connection.effectiveType);
});

(2) Compatibility:

The compatibility of connection is relatively low, so choose carefully when using it.
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_48896417/article/details/132377821