javascript 在 JS 中检查互联网连接的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10426851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:51:02  来源:igfitidea点击:

Quickest way to check internet connectivity in JS

javascript

提问by gaganHR

I have this code in a html file that checks for connectivity, but the problem here is that it takes about 10 seconds to throw the alert message box to indicate the connection is lost. I want to know if there's a much faster way to inform the user that the connection is lost without having to wait. Strictly JS thanks...

我在检查连接的 html 文件中有此代码,但这里的问题是抛出警报消息框以指示连接丢失需要大约 10 秒。我想知道是否有一种更快的方法来通知用户连接丢失而无需等待。严格的JS谢谢...

JS code:

JS代码:

<script language="JavaScript">
function SubmitButton()
{
    if(navigator.onLine)
    {
            document.getElementById('SubmitBtn').style.visibility='visible';
    }
    else
    {
        document.getElementById('SubmitBtn').style.visibility='hidden';
    }
}
function Online() 
{ 
    var status=false;
    status= navigator.onLine;
    if(status!= true)
    {
        alert('Network connectivity is lost, please try again later');
    }
}
</script>

Calling it in html file here:

在 html 文件中调用它:

<INPUT name="ccMCA1input" type="checkbox" onclick="ccMCA1.ccEvaluate(),Online()" value=False>

采纳答案by Rob W

navigator.onLineis the only built-in property which can be checked (and not reliable btw).
You could create a XHR request to a reliable server, and check whether any response is being received.

navigator.onLine是唯一可以检查的内置属性(顺便说一句,不可靠)。
您可以向可靠的服务器创建 XHR 请求,并检查是否收到任何响应。

回答by Joseph

You could periodically request a 1x1 gif image from a(ny) server, making sure you use the cache buster methodto avoid caching. You could use the onloadand onerrorevents.

您可以定期从(纽约)服务器请求 1x1 gif 图像,确保使用缓存破坏器方法来避免缓存。您可以使用onloadonerror事件。

var isOnline = (function isOnline(){
  // Create a closure to enclose some repeating data
  var state = false;
  var src = 'gif_url?t=' + Date.now();
  var function onLoad = function(){state = true;}
  var function onError = function(){state = false;}

  // Inside the closure, we create our monitor
  var timer = setInterval(function(){
    var img = new Image();
    img.onload = onLoad;
    img.onerror = onError;
    img.src = src;
  }, 10000);

  // Return a function that when called, returns the state in the closure
  return function(){return state;};
}());

//Use as
var amIOnline = isOnline();