How to check if the user is online using javascript or any library?

Stranger B. picture Stranger B. · Apr 22, 2015 · Viewed 16.1k times · Source

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 :

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

Answer

Jamie Barker picture Jamie Barker · Apr 22, 2015

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.