Several Methods for judging the current network connection status using JS in the browser, and several js Methods
The following describes how to use JS to determine the current network status in a browser:
1. navigator. onLine
2. ajax request
3. Obtain Network Resources
4. bind ()
1. navigator. onLine
Use navigator. onLine to determine the current network status:
if(navigator.onLine){ ...}else{ ...}
Very simple, but not accurate-according to the MDN description:
Navigator. onLine returns false only when the machine is not connected to the LAN or vro. Otherwise, true is returned.
That is to say, after the machine is connected to the router, even if the router is not connected to the network, navigator. onLine still returns true.
2. ajax request
The get request method is used to determine whether data can be successfully obtained based on the returned value, so as to determine the current network status:
$.ajax({ url: 'x.html', success: function(result){ ... }, error: function(result){ ... }});
3. Obtain Network Resources
The principle is the same as 2. Place a hidden image on the page and set its onerror function (this function is called when the image resource acquisition fails ):
<script src="./jquery-3.1.1.min.js"></script><script>function getImgError(){ alert("Network disconnect!");}$().ready(function(){ $("#btn-test").click(function(){ var imgPath = "https://www.baidu.com/img/bd_logo1.png"; var timeStamp = Date.parse(new Date()); $("#img-test").attr("src", imgPath + "?timestamp=" + timeStamp); });});</script><body> <button id="btn-test">check status</button></body>
Each time you click a button, the image's src is updated. If an error occurred while obtaining the image, the network connection is considered failed.
The accuracy of network status determination depends on the stability of image resources...
4. bind ()
Same principle 1:
var netStatue = true;$(window).bind('online', function(){ netStatue = true;});$(window).bind('offline', function(){ netStatue = false;});...if(netStatue){ ...}else{ ...}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.