Skip to content

Instantly share code, notes, and snippets.

@Coornail
Forked from louisremi/serverReachable.js
Created September 17, 2011 10:33
Show Gist options
  • Save Coornail/1223830 to your computer and use it in GitHub Desktop.
Save Coornail/1223830 to your computer and use it in GitHub Desktop.
better navigation.onLine: serverReachable()
function serverReachable() {
// Cross-browser XHR creation
var request = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ),
status_code;
request.open(
// requesting the headers is faster, and just enough
"HEAD",
// append a random string to the current hostname,
// to make sure we're not hitting the cache
"//" + window.location.hostname + "/?rand=" + Math.random(),
// make a synchronous request
false
);
try {
request.send();
status_code = request.status;
// Make sure the server is reachable
return ( status_code >= 200 && status_code < 300 || status_code === 304 );
// catch network & other problems
} catch (e) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment