avatarMate Marschalko

Summary

The web content discusses the importance and methods of handling online and offline events in JavaScript, focusing on the use of the navigator.onLine property and event listeners for 'online' and 'offline' events to enhance user experience on mobile devices.

Abstract

The article titled "Online and Offline events with JavaScript" emphasizes the need for front-end developers to manage internet connectivity issues, particularly on mobile websites where connections can be unstable. It provides an overview of JavaScript's capabilities to detect and respond to changes in network status using the navigator object's onLine property. The author argues that while libraries exist for this purpose, supporting mobile browsers is crucial. The article demonstrates how to use event listeners for 'online' and 'offline' events to execute specific functions when the network status changes, rather than relying on periodic checks with setInterval(). It also shows how to measure the duration of an offline period using timestamps from these events, converted to human-readable formats with the Date() object. The author concludes by encouraging developers to explore additional features of the navigator object to further improve user experience.

Opinions

  • The author believes that handling internet connectivity is often overlooked by front-end developers, despite its significance for mobile website users.
  • There is a preference expressed for direct JavaScript implementation over using libraries like offline.js, especially since mobile device support is deemed more important.
  • The author suggests that constantly monitoring network status with setInterval() is less efficient than using event listeners, which only trigger functions upon a change in connection status.
  • The article conveys that the navigator object's properties and methods, such as navigator.onLine and event timestamps, are underutilized and deserve more attention from developers.
  • The author values the user experience and advocates for the implementation of features that provide feedback and information to users when they lose or regain their internet connection.

Online and Offline events with JavaScript

Not many websites handle lost Internet connection and give the user feedback and information but this question should be looked at more often by front-end developers especially when working on mobile websites.

Checking the Internet connection with Javascript is easier than you think. When I first looked at this topic found many libraries like offline.js and others that give you IE8 and desktop browser support but I don’t really see the point. The most important is to give support for mobile devices as that’s where the Internet connection could be unreliable. The below example code will work on most mobile browsers. I works perfectly on Android 2 and better, iOS 6 and better, Blacbkerry 7 and 10 and of course all modern desktop browsers.

“Checking the Internet connection with Javascript is easier than you think…”

Checking the connection status

The navigator global object has many useful properties and methods and the one that we most often use is navigator.userAgent to get the user’s browser and operating system version.

Apart from that it has another one that happens to return true or false depending on whether the device is connected to the network or not:

var connected = navigator.onLine; // this will be true or false

Listening for events

Navigator.onLine does the job but ideally we’d like to constantly monitor the status of the network and we don’t want to check the value in a setInterval() periodically. Instead, we want to setup event listeners to execute functions only when the Internet connection changes.

window.addEventListener('offline', function(event){
    console.log("You lost connection.");
});
window.addEventListener(‘online’, function(event){
    console.log("You are now back online.");
});

Let’s try moving that function outside the event listener and handle both events within the same function. In order to do that we will need information about the event and we can get that information from the automatically passed in event attribute.

function handleConnectionChange(event){
    if(event.type == "offline"){
        console.log("You lost connection.");
    }
    if(event.type == "online"){
        console.log("You are now back online.");
    }
    
    console.log(new Date(event.timeStamp));
}
window.addEventListener('online', handleConnectionChange);
window.addEventListener('offline', handleConnectionChange);

Now both event listeners call handleConnectionChange when the connection changes and both event listeners pass in the event object for the function with the information about the event. First we used event.type and checked if it’s value is either “online” or “offline” and sent a customised message to the console.

The second thing we used from the event object is the timestamp. This is a very long number that represents the time in milliseconds when the event was fired. Luckily we can use the javascript Date() object to convert this to a human readable format.

Measuring offline time

Finally, if you want to check how long was the user offline you can simply store both online and offline timestamps in a JavaScript Date() instance and by simply subtracting the two variables you can get the offline time period in milliseconds. If you divide milliseconds by 1000 you will get the time in seconds. Here’s how I would go about doing all this:

var wentOffline, wentOnline;
function handleConnectionChange(event){
    if(event.type == "offline"){
        console.log("You lost connection.");
        wentOffline = new Date(event.timeStamp);
    }
    if(event.type == "online"){
        console.log("You are now back online.");
        wentOnline = new Date(event.timeStamp);
        console.log("You were offline for " + (wentOnline — wentOffline) / 1000 + "seconds.");
    }
}
window.addEventListener('online', handleConnectionChange);
window.addEventListener('offline', handleConnectionChange);

Detecting the network connection is a very useful feature and we should always think about how we can improve the users experience with this extra information.

It’s probably also worth checking out what else can be found on that navigator object…

JavaScript
Web Development
API
Recommended from ReadMedium