The fastest way to check the connection status in the browser

I am using a web application from which I post data to the server very often. The option to send data should be disabled if the app does not have an internet connection. What's the fastest way to check your browser if you're online? I have used navigator.onLine

but it is unreliable because different browsers interpret it differently. My other solution was to put some simple file on the server and an attemp to reach it every time before sending. The code looked like this:

function serverReachable() {
  var x = new XMLHttpRequest (),
  s;
  x.open(
    "HEAD",
    'http://servername/client/keepalive.txt',
    false
  );
  try {
    x.send();
    s = x.status;
    return ( s >= 200 && s < 300 || s === 304 );
  } catch (e) {
    return false;
  }
}

      

The serverReachable () function does the job, but is there a faster way to do it (faster I mean faster in terms of time, not amount of code)?

+3


source to share


3 answers


using

navigator.onLine

      



to check if there is still an internet connection it should return True or False.

+1


source


I usually try to create Image()

and then listen to the onerror

/ event onload

.

function isOnline(cb){
    var img = new Image();
    img.onerror = function() {
        cb(false)
    }
    img.onload = function() {
        cb(true)
    }
    img.src = "http://example.com/some_image.jpg?t=" + (+new Date);
}
isOnline(function(res){
    if (res) {
        // yup!
    } else {
        // nope
    }
});

      



This is, however, most likely under the hood, exactly the same as for an XHR request. You will have to play around and see what suits you best.

EDIT: Added a timestamp to force the non-cached version.

+1


source


The fastest way to check if your server is connected or not,

Try to access any file on your server like any image.

function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "img/a.png"; //image path in your project
    var randomNum = Math.round(Math.random() * 10000);
    xhr.open('HEAD', file + "?rand=" + randomNum, false);
    try {
        xhr.send(null);
        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

      

Note. To speed up this call, the image ( a.png

) you are trying to load should be very lightweight; in KB.

0


source







All Articles