amidzic89
amidzic89

Reputation: 83

Fastest way to check connection status from browser

I'm using web app from which i send data to server very frequently. Option for sending data should be disabled if app has no internet connection. Which is the fastest way to check from browser if you are online? I've used navigator.onLine but it's unreliable because different browsers interpret it differently. My other solution was to put some plain file on server and attemp to reach it every time before sending. 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;
  }
}

Function serverReachable() does the job but is there any faster way to do this(by faster I mean faster in terms of time not code quantity)?

Upvotes: 3

Views: 6565

Answers (3)

Eric
Eric

Reputation: 18922

I usually try to create an Image() then listen for the onerror/onload event.

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 making a XHR-request. You will have to fiddle and see what suits you best!

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

Upvotes: 1

Vikrant
Vikrant

Reputation: 5046

Fastest way to check your server is connected or not is,

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 make this call faster, image (a.png), you are trying to download should be very light; in KBs.

Upvotes: 0

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

use

navigator.onLine

to check if there is internet connection on yet, it should return True or False.

Upvotes: 1

Related Questions