Skip to content

Instantly share code, notes, and snippets.

@zikkeung
Created January 20, 2014 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zikkeung/e370e17af982a39dbff2 to your computer and use it in GitHub Desktop.
Save zikkeung/e370e17af982a39dbff2 to your computer and use it in GitHub Desktop.
javascript检测网络连接是否正常
function doesConnectionExist(file) {
var xhr = new XMLHttpRequest();
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
doesConnectionExist("http://www.yoursite.com/somefile.png");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment