且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用javascript或任何库检查用户是否在线?

更新时间:2023-12-02 16:09:52

我想你应该试试 OFFLINE.js ..它看起来很容易使用,只需试一试。



它甚至提供选项 checkOnLoad ,它会在页面加载时立即检查连接。


Offline.check():检查连接的当前状态。



Offline.state:连接的当前状态'up'或'down'


还没试过,会很好知道它是否按预期工作。



EDIT 在代码中占了一席之地,它使用失败的XHR请求方法建议在这个 SO问题


I need some help on how I could check the internet connection using Javascript or jQuery or any library if available. cause i'm developing an offline application and I want to show a version if the user is offline and another version if the user is online.

For the moment i'm using this code :

if (navigator.onLine) {
    alert('online');
} else {
    alert('offline');
}

But this is working very slow to detect. sometimes it's just connected to a network without internet, it takes 5 to 10 seconds to alert false (No internet).

I took a look at Offline.js library, but I'm not sure if this library is useful in my case. and I don't know how to use it

i think you should try OFFLINE.js.. it looks pretty easy to use, just give it a try.

it even provides the option checkOnLoad which checks the connection immediately on page load.

Offline.check(): Check the current status of the connection.

Offline.state: The current state of the connection 'up' or 'down'

haven't tried it, would be nice to know if it works as intended.

EDIT took a little peak into the code, it uses the method with FAILED XHR REQUEST suggested in THIS SO Question