标签:date 相关 targe mda color prism 查询 edit 没有
文件大小(KB) * 1000 /( end -start )
就可以计算出网速了(KB/S)。
navigator.connection.downlink * 1024 / 8
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 }); }
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 }); }
function getSpeedWithDnlink() { // downlink测算网速 const connection = window.navigator.connection; if (connection && connection.downlink) { return connection.downlink * 1024 / 8; } }
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; }) }
npm i network-speed-test
使用方式
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();
https://juejin.im/post/5b4de6b7e51d45190d55340b
标签:date 相关 targe mda color prism 查询 edit 没有
原文地址:https://www.cnblogs.com/penghuwan/p/11366446.html