Javascript Check Internet Connection

99% of people used to type google.com immediately after opening their web browser to check internet connection. This is very true in our morden world. Now a days we can’t live without an Internet. While browing, If you lose the connection then you will feel sad and unhappy till the connection is UP.

In this tutorial, I’m going to explain how to check Internet connection exists or not by using pure Javascript plugin called  offline.js . This javascript plugin will notify the user whenever they lost the internet connection like Gmail. Check my previous popular post on – Gmail Style Inbox Design using jQuery & CSS

By using simple ajax call, it tell us the internet connection is up or down. Also it notify them when the connection is up.

javascript check internet connection

 

How it Works?

It keeps on sending Ajax request to load an Image (1 byte in size) to check the connection. If that ajax call receives 200 Ok status code, then internet connection is UP. If it returns 204 No Content status code, then Internet connection is Down.

Please place the below javascript before  </body>  tag

<script src="https://cdnjs.cloudflare.com/ajax/libs/offline-js/0.7.19/offline.min.js"></script>

Load the below stylesheet before  </head>  tag. 1st css is for styling the theme. 2nd css is for language content.

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/offline-js/0.7.19/themes/offline-theme-slide.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/offline-js/0.7.19/themes/offline-language-english.min.css" />

Now please this javascript before  </body>  tag.

Offline.options = {checks: {xhr: {url: '/tiny-image.gif'}}};

You should replace your image with less in size. or download this image – https://d1v5pkn4fpocaq.cloudfront.net/downloads/tiny-image.gif

Check Internet Connection with Pure Javascript

Please check the live demo to see how it is working beautifully. With few lines of code and one single tiny image can help you to make this feature go live in a minute.

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

4 thoughts on “Javascript Check Internet Connection”

  1. I had implemented this demo but is is showing error of CORS origin resource sharing error : MissingAllowOriginHeader…that’s why if interner is connected then it does not show your device is connected please guide me how to solve this.

    Reply

Leave a Comment