title: JavaScript/Ajax: navigator.onLine alternative: serverReachable()
body: <p>The following code is an alternative to using navigator.onLine - by checking whether the server is reachable.</p>
  
  <p>'Simple' question - how do I make it work?</p>
  
  <pre><code>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 &gt;= 200 &amp;&amp; s &lt; 300 || s === 304 );
    // catch network &amp; other problems
    } catch (e) {
      return false;
    }
  }
  </code></pre>
  
  <p>The above code was taken from the article: <a href="http://louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/" rel="nofollow">http://louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/</a> but I can't work out why it doesn't work.</p>