Javascript detects if the implementation code is networked

  • 2020-03-30 04:00:51
  • OfStack

The simplest way to do this is to load network resources, JS files, or image files.


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
typeof window.jQuery === "undefined" // return false or ture

Use the jQuery variable to detect whether you are networked


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());

So you have to add a compatible method: send an HTTP header request to the location.hostname address, with the following code:


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 is that the third argument to the open method to pass false must be a synchronous request.

Original articles, reproduced please indicate: reproduced from (link: http://www.javascript100.com)


Related articles: