It’s hard to give a great experience on the web when the browser is offline. It’s more like trying to enjoy a party without being there. Of course, we could pretend like we have no idea offline is inevitable, look over billions of people living in offline-first regions and design solely for online.
Or we could also do a few things to make offline less painful.
That’s what this post is about; detecting and communicating changes in connectivity to your users. It’ll save you a lot of brand value if people know when it’s their network and not your app.
Why Worry About Offline? Think of this scenario;
A user is browsing your web app, suddenly, their WIFI goes off. 2 things could happen depending on the kind of experience we want to give.
Nothing happens. The user has no idea they’re offline till they click something and everything breaks on them. The app immediately communicates their connectivity state, signifying possible actions while offline. You want to avoid the first scenario.
If a user is clicking your app and nothing’s happening, that’s bad experience. Exactly what you don’t want. Plus, a huge percentage of people on the internet are on 3g. It get’s crazier in Next Billion Regions, where most internet users are offline-first and majorly 2g.
Experiences on the web are in real-time; Users expect them to be fast, responsive and show fresh content every time. If the user isn’t able to get fresh content, we have to somehow tell them that what they’re seeing is old and can only be updated when there’s internet connection. This way, we make our apps reliable and responsive.
Online & Offline Events The offline event fires when a user goes Offline, and the online event fires when they come back Online (fired on the window object). When combined with navigator.onLine, we can attach event handlers and more efficiently communicate connection states
Here’s a simple example of the event listeners at work
const handleOffline = e => console.log(navigator.onLine) const handleOnline = e => console.log(navigator.onLine)
window.addEventListener(“offline”, handleOffline) window.addEventListener(“online”, handleOnline) The code will log a Boolean to the browser depending on the connectivity state. If the user goes offline, handleOffline event handler will fire and when they come back online, handleOnline will fire.
Navigator.onLine The navigator.onLine property holds the current connection state of the user. It equals true if the user is online (can connect to the network) and false if they’re offline (can’t connect to the network).
In The Real World