How To Check If Internet Connection Exists In jQuery & Javascript


Read {count} times since 2020

If you are running an app on the web that requires Internet Connection all the time, sometimes the internet connection will fail on the client side and your app won’t properly work. The best example is the New Tab Chrome Apps that will display the URL icons grayscale when offline and will make the icons back to color when online. To check whether the client’s internet connection is online, we use jQuery. You can also use Javascript to check. I will tell you how to do the checking in both jQuery and Javascript.
The checking is simple. We will send a request to one of the site’s image. If the request was successful, the Internet Connection is active and if it’s not successful, there isn’t any active Internet Connection. It’s as simple as that. The following modal will make you understand the concept easily :

I have wrapped the checking into a function named checkNetConnection.

Javascript

function checkNetConnection(){
 var xhr = new XMLHttpRequest();
 var file = "http://yoursite.com/somefile.png";
 var r = Math.round(Math.random() * 10000);
 xhr.open('HEAD', file + "?subins=" + r, false);
 try {
  xhr.send();
  if (xhr.status >= 200 && xhr.status < 304) {
   return true;
  } else {
   return false;
  }
 } catch (e) {
  return false;
 }
}

jQuery

function checkNetConnection(){
 jQuery.ajaxSetup({async:false});
 re="";
 r=Math.round(Math.random() * 10000);
 $.get("http://yoursite.com/somefile.png",{subins:r},function(d){
  re=true;
 }).error(function(){
  re=false;
 });
 return re;
}

In Both Codes above you have to change the URL

http://yoursite.com/somefile.png

to a small Image file location of your site. If you want a small size image (137 bytes) go to https://demos.subinsb.com/cdn/dot.png.
If you have any suggestions / problems report it to me via comments. I am here 10/7.