DEV Community

Carmen Bourlon
Carmen Bourlon

Posted on

Let's take this offline: determine internet connection

This post originally appeared on carmalou.com

More than 10 percent of Americans are without home internet. As such, it's really important to be considerate of users with inconsistent internet. A user is without internet is effectively stuck on an island, unable to communicate with the outside world.

One of the simplest things we can do is check for network connection. To do this we can use: navigator.onLine. This function -- which is built into the JS spec and also has great cross-browser compatibility -- returns a boolean value based on whether or not the user has a network connection. It might look like this:

if(navigator.onLine) {
  console.log("User is online!");
} else {
  console.log("User is not online. :(");
}

This is really handy because we can test for this before running any ajax calls and offer the user a much nicer experience because they won't lose connection and suddenly hit a bunch of connection errors.

We can set up an event listener and continuously monitor network connection.

window.addEventListener('offline', function(event) {
  console.log("We are offline! :(");
});

window.addEventListener('online', function(event) {
  console.log("We are online! :)");
});

While no network connection will mean you are not on the internet, a true value can be misleading. Just because you are on a network doesn't mean you have internet connection -- for instance you can be on an internal network but the network doesn't have an external internet connection. This might return true.

So what can we do to test if our true is actually true? If we get true, we can test if we can access an image.

fetch('some/img/url/here').then(
    function(response) {
      console.log(response);
    })
    .catch(function(err) {
      console.log(err);
    });

And when we look at the response, we can see the status code. If you have no connection, the catch will return your error with something like TypeError: Failed to fetch.

And there you have it! You can check for network connection with navigator.onLine, and to be sure you are truly online, you can use fetch to pull an image and check the status code.

This post originally appeared on carmalou.com

Top comments (0)