DEV Community

Carmen Bourlon
Carmen Bourlon

Posted on

3 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay