The simplest and most crude way is to load network resources, JS files or picture files.
The code copy is as follows:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
typeof window.jQuery === "undefined" // return false or truth
Use jQuery variable to detect whether it is connected to the Internet
function doConnectFunction() { return true;}function doNotConnectFunction() { return false;} var i = new Image();i.onload = doConnectFunction;i.onerror = doNotConnectFunction;i.src = 'http://su.bdimg.com/static/superplus/img/logo_white.png?d=' + escape(Date());The problem with loading network resources is the detection of the Internet. If it is LAN detection, it is powerless.
At this time, a better solution is needed, and navigator.onLine is used. This attribute is more tricky. The browser compatibility is perfectly supported by chrome and Safari, and IE7 or above. Firefox and IE6 are tricky. They only return false when the browser is "offline" and all others return true. All the network cables are true, and Opera doesn't support them directly.
So you have to add a compatible method: send an http header request to the location.hostname address, the code is as follows:
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );var status;xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false ); try { xhr.send(); return ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ); } catch (error) { return false; }One thing to note in this is that the third parameter of the open method must be passed false, and it must be a synchronous request.
Summary: For browsers that support navigator.onLine, use navigator.onLine, and send an http header request if it does not support it.
Original articles, please indicate the reprint: Reprinted from front-end development