PrefaceHere's the thing. I recently tried to write a library that determines the current network speed and controls the range of requests on the front end to request a large file in steps. I haven't written a single line of code for this thing yet, not only because I suddenly realized that the idea of this requirement is a bit impractical, but also because I suddenly asked myself - how should the front end determine the network speed? ? ?! Summary of the principle of front-end judgment of network speed(Note: The default unit of the network speed below is KB/S) By consulting relevant information, I found that the ideas are mainly divided into the following categories: 1. Calculate network speed by loading img or initiating Ajax requestBy requesting a file in the same domain as the server, such as a picture, the two time points of starting the request and receiving the response are marked by Date.now, because Date.now is the number of milliseconds from January 1, 1970 (UTC) to the current time, so we use end - start to find the time difference (ms), and then calculate:
You can calculate the network speed (KB/S). There are two ways to request files: loading through img or loading through AJAX:
2.window.navigator.connection.downlink network speed queryWe can also achieve this through some advanced H5 APIs, for example, here we can use window.navigator.connection.downlink to query, but as you know, this kind of API has its own characteristics, that is, the old compatibility issues, so we usually use it as a reserve means, through capability detection, if it can be used, use it, if it can't be used, use other methods. And it should be noted that the unit of downlink is mbps, and the formula for converting it to KB/S is
It is understandable to multiply by 1024, but why do we need to divide by 8 afterwards? This is because the "b" in mbps refers to bit, and the "B" in KB/s refers to Byte. 1 byte (b) = 8 bits, so we need to divide by 8. 3. Generally speaking, network speed is measured by requesting filesThere may be errors in a single request, so we can request multiple times and calculate the average. Front-end method for judging network speed and its advantages and disadvantages
img loading speed testfunction 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 speed test 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 test function getSpeedWithDnlink() { // downlink calculates network speed const connection = window.navigator.connection; if (connection && connection.downlink) { return connection.downlink * 1024 / 8; } } Comprehensive speed test function getNetSpeed(url, times) { // downlink calculates network speed const connection = window.navigator.connection; if (connection && connection.downlink) { return connection.downlink * 1024 / 8; } //Measure speed multiple times to find the average value 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; }) } I have published an npm package for the above code, which can be downloaded via npm i network-speed-test How to use import * from 'network-speed-test'; getSpeedWithImg("upload/2022/web/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(); npm package addresshttps://www.npmjs.com/package/network-speed-test Github addresshttps://github.com/penghuwan/network-speed-test The above is the details of how to use JavaScript to measure network speed. For more information about using JavaScript to measure network speed, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: How to configure /var/log/messages in Ubuntu system log
>>: How to install MySQL server community version MySQL 5.7.22 winx64 in win10
It is troublesome to install the db2 database dir...
Table of contents introduction Distinguish betwee...
1. Overview The image in Docker is designed in la...
Install Nginx on Docker Nginx is a high-performan...
The floating-point types supported in MySQL are F...
Preface If you use the overflow: scroll attribute...
1. Introduction Recently I found that there are m...
High CPU load caused by MySQL This afternoon, I d...
Table of contents 01 Introduction to Atomic DDL 0...
Table of contents Preface 1. MySQL master-slave r...
Recommended Docker learning materials: https://ww...
Preface: To store multiple elements, arrays are t...
Table of contents Solution: 1. IGNORE 2. REPLACE ...
Table of contents 1. Install node 2. Install Comm...
Table of contents Preface The need for online XML...