Created
December 10, 2012 14:00
-
-
Save gitawego/4250714 to your computer and use it in GitHub Desktop.
a simple way to detect if server is reachable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//event naviagor.onLine isn't fiable. | |
function serverReachable() { | |
// IE vs. standard XHR creation | |
var x = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ), | |
s; | |
x.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 { | |
x.send(); | |
s = x.status; | |
// Make sure the server is reachable | |
return ( s >= 200 && s < 300 || s === 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