从浏览器检查连接状态的最快方法 [英] Fastest way to check connection status from browser

查看:47
本文介绍了从浏览器检查连接状态的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络应用程序,我经常从该应用程序向服务器发送数据.如果应用没有互联网连接,则应禁用用于发送数据的选项.如果您在线,从浏览器检查的最快方法是哪种?我使用过 navigator.onLine ,但是它不可靠,因为不同的浏览器对它的解释不同.我的另一个解决方案是在服务器上放置一些纯文件,并在每次发送之前尝试每次访问它.代码看起来像这样:

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;
  }
}

功能serverReachable()可以完成工作,但是有没有更快的方法(更快,我指的是时间,而不是代码量)?

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

推荐答案

我通常尝试创建 Image(),然后侦听 onerror / onload事件.

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
    }
});

然而,这很可能是在幕后,与发出XHR请求完全相同.您将不得不摆弄,看看最适合您的!

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!

添加了时间戳以强制使用非缓存版本.

Added timestamp to force a non-cached version.

这篇关于从浏览器检查连接状态的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆