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 just got this bit of code functionality from a Mozilla Site:
window.addEventListener('load', function(e) { if (navigator.onLine) { console.log('We\'re online!'); } else { console.log('We\'re offline...'); } }, false); window.addEventListener('online', function(e) { console.log('And we\'re back :).'); }, false); window.addEventListener('offline', function(e) { console.log('Connection is down.'); }, false);
They even have a link to see it working. I tried it in IE, Firefox and Chrome. Chrome appeared the slowest but it was only about half a second.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With