Home > Web Front-end > JS Tutorial > js detection network status code arrangement

js detection network status code arrangement

PHP中文网
Release: 2017-07-13 14:11:03
Original
2299 people have browsed it

This article implements the use of javascript to detect whether the mobile phone network is interrupted, and to realize certain page reminders or function disabling, thereby optimizing the user experience.

There is code and there is truth. The code is as follows:

 /*检测网络状况*/
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);
/*检测网络状况*/
Copy after login

By continuously requesting a 1-pixel image, if the image request fails, the img.onerror event is triggered, and the event is being called back Modify the global variable testnet_on=0, indicating that the network is disconnected, otherwise the onload event will be triggered, testnet_on=1.

Of course, the picture cannot be too large, otherwise it will waste user traffic, cause user resentment, and the gain outweighs the gain. coming.

This article is provided by php Chinese website,

Article address: http://www.php.cn/js-tutorial-374005.html

Please do not reprint~~ ~

The above is the detailed content of js detection network status code arrangement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template