If you want to learn everything you need to know about service workers, head over to serviceworkerbook.com and order my book, “Let’s Take This Offline”! Be sure to use navigator-online for 10% off!

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.


console.log("We are offline! :(");
});

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.

Thanks so much for reading! If you liked this post, you should head on over to serviceworkerbook.com and buy my book! Be sure to use navigator-online for 10% off!