当前位置:Gxlcms > JavaScript > js检测网络状况代码整理

js检测网络状况代码整理

时间:2021-07-01 10:21:17 帮助过:6人阅读

本文实现了用javascript检测手机网络是否中断,实现某些页面提醒或功能禁用,从而优化用户体验。

有代码有真相,代码如下:

 /*检测网络状况*/
var testnet_on=function(){
var img=new Image();
img.id="testnet";
img.onload=function(){
  $("#testnet").remove();
  if(net_on==0 && $("#playbtn").is(":not(.stopped)")){
    playmusic(currentinfo.id);
  }
  net_on=1;
};
img.onerror=function(){
  $("#testnet").remove();
  net_on=0;
};
img.src="http://www.baidu.com/img/baidu_jgylogo3.gif?t="+(new Date().getTime());
img.style.display="none";
document.body.appendChild(img);
}
var net_on=1;
test_interval=setInterval(testnet_on,10000);
/*检测网络状况*/

通过不断请求1个像素的图片,如果图片请求失败,触发img.onerror事件,事件回调中修改全局变量testnet_on=0,说明断网了,否则触发onload事件,testnet_on=1.

当然图片不能太大,不然浪费用户流量,会导致用户反感就得不偿失来了。

本文由Gxl网提供,

文章地址:http://www.gxlcms.com/js-tutorial-374005.html

请勿转载~~~

以上就是js检测网络状况代码整理的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行