A nice image used for demonstration of SW work.

Every now and then we hear about optimizing something. There are different kinds of optimizations we could do to make our apps faster and more efficient. To save time or memory. This article will cover one of those methods — service workers.

TL;DR

This tutorial explains what a service worker is and how to use it. In JavaScript. There is a code example at the end of it. If you want to skip the reading, here is the Git repo and here you may see a live demo.

The Theory

Let’s see first what a worker is this 👀 and what service can we use it for 🤓.

The service worker is a simple script. JavaScript code, that your browser runs in the background, separate from a web page. It’s very convenient to use service workers for features that don’t need a web page or user interaction. One of the most common usages is intercepting and handling network requests. Which includes managing a cache of responses. The following is a simple example of how to include a service worker in your application run.

Usually, in the entry point of your app, you put this:

if ('serviceWorker' in navigator) {

window.addEventListener('load', function() {

navigator.serviceWorker.register('/service-worker.js');

});

}

This way of using service workers is a little bit improved than the basic one. Which would be directly calling the register() method inside the if statement. In this case, we use the window load event to register the service worker after the page has finished loading. After doing this, you need to add your service worker code in service-worker.js file. At this point, you might want to take a look at mine service worker file here.

All major browsers support Service Workers now and you can start using them right away.

The Example

Enough theory, let’s build a real example app, that will leverage the service workers feature.

Let’s imagine we are building an app that needs to load a big chunk of data. It could be, for example, a nice, big full-screen image, we would display on the front page. Or it could be a big video clip we have to wait to load. This is an ideal use case for a service worker to shine. Let’s see how. 👀

In our specific case, we will use the clock time to show the benefit of using service workers. What I mean is, that we will build a simple app, showing the time. It will have a nice, big button for fetching a nice, big image. And it will provide the user with an option to choose to use or not a service worker.

Here is a screenshot of how it looks like.