Skip to content

Instantly share code, notes, and snippets.

@tspringborg
Last active December 19, 2015 07:19
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 tspringborg/5917663 to your computer and use it in GitHub Desktop.
Save tspringborg/5917663 to your computer and use it in GitHub Desktop.
navigator.onLine is not a good way to test if the client is connected to the internet in an html5 offline application
var serverReachable = function() {
// 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