便利的响应式网站建设,速贝网站友情链接怎么做,广东自考网站建设管理,深圳公司招聘网最新招聘信息前端判断用户当前网络状态和判断网速 一、第一种是通过 HTML5 提供的 navigator 去检测网络(1)、原理介绍:(2)、兼容性 二、监听window.ononline和window.onoffline事件:三、通过ajax进行请求判断(兼容性好-推荐)(1)、原理介绍:(2)、注意: 四、navigator.connection方法监听网络… 前端判断用户当前网络状态和判断网速 一、第一种是通过 HTML5 提供的 navigator 去检测网络(1)、原理介绍:(2)、兼容性 二、监听window.ononline和window.onoffline事件:三、通过ajax进行请求判断(兼容性好-推荐)(1)、原理介绍:(2)、注意: 四、navigator.connection方法监听网络变化(1)、原理介绍:(2)、兼容性: 前端必备工具推荐网站(免费图床、API和ChatAI等实用工具): http://luckycola.com.cn/ 一、第一种是通过 HTML5 提供的 navigator 去检测网络
(1)、原理介绍:
通过window.navigator.onLine属性返回的是布尔值。true表示在线false表示离线。onLine属性只能简单判断网络的断开和连接状态而不能监听网络状态的变化例如从4g到3g。 if (window.navigator.onLine) {console.log(网络正常);} else {console.log(网络中断);}
(2)、兼容性 二、监听window.ononline和window.onoffline事件:
script typetext/javascriptwindow.addEventListener(offline,function(){alert(网络连接恢复);})window.addEventListener(online,function(){alert(网络连接中断);})
/script或者这样写script typetext/javascriptwindow.ononlinefunction(){alert(网络连接恢复);}window.onofflinefunction(){alert(网络连接中断);}
/script三、通过ajax进行请求判断(兼容性好-推荐)
(1)、原理介绍:
这种方式的原理是通过ajax请求一张较小的资源和资源返回消耗的时长计算出当前网络的速度,所以兼容性较好,也可以得到具体的网速值,是一种比较好的解决方案
(2)、注意:
但是这种方案有一个注意点就是用来测速的图片资源必须小(十几K足够了),因为太大会导致测速耗时过长导致业务阻塞
/ 判断网速 kb
export function measureBW(): Promisenumber {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)}});
}四、navigator.connection方法监听网络变化
(1)、原理介绍:
能监听到具体的网络变化例如从4g变化到了3g但不能监听到是离线状态还是在线状态。 const connection navigator.connection || navigator.mozConnection || navigator.webkitConnection;connection.addEventListener(change, () {// connection.effectiveType返回的是具体的网络状态4g/3g/2gconsole.log(connection.effectiveType);
});(2)、兼容性:
connection的兼容性比较低,谨慎选择使用
相关文章: