Fastest way to check connection status from browser

こ雲淡風輕ζ 提交于 2021-01-27 13:39:32

问题


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)?


回答1:


use

navigator.onLine

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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/29823759/fastest-way-to-check-connection-status-from-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!