Home > Web Front-end > JS Tutorial > Implementation code for javascript detection of Internet access_javascript skills

Implementation code for javascript detection of Internet access_javascript skills

WBOY
Release: 2016-05-16 16:35:07
Original
1240 people have browsed it

The simplest and crudest way is to load network resources, JS files or image files.

Copy code The code is as follows:


typeof window.jQuery === "undefined" // return false or true

Use jQuery variables to detect whether you are 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());
Copy after login

The problem with loading network resources is the detection of the Internet. If it is a LAN detection, there is nothing you can do.
At this time, we need a better solution, so we need to use navigator.onLine. The disadvantage of this attribute is that it is compatible with browsers. Chrome and Safari all support it perfectly, and IE7 and above are supported. Firefox and IE6 are more pitiful. They only return false when the browser is "offline", and return true otherwise. It is true even if the network cable is pinched, but Opera no longer supports it.

So we have to add a compatibility 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;
 }
Copy after login

One thing to note is that the third parameter of the open method must be passed false, and it must be a synchronous request.

Summary: If the browser supports navigator.onLine, use navigator.onLine. If it does not support it, send an http header request.

Original article, please indicate when reprinting: Reprinted from Front-end Development

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