Sign in

Understanding Service Workers — The JavaScript Type

Introduction

What is a service worker and do we need to tip them? Actually… today, we’re talking about a different kind of service worker.

The kind of service worker we are talking about is a type of web worker. At a high-level, a service worker is essentially a script that is stored in a client’s browser. It is event-driven, meaning that it intercepts and listens to all traffic going to and coming from the client’s browser. If needed, it can perform some action in response to these events. It’s primary purpose is to act as a proxy between the network, the client, and a cache.

Simple illustration of a service worker as a proxy between the app, the cache and the server (drawn by me)

What are service workers?

In simple terms, a service worker is a JavaScript file that is stored in a client’s browser. As mentioned before, they are a type of web worker. However, service workers are specialized in caching content and setting up offline behavior for when the user does not have a network connection. For example, assuming a user is not connected, when the user attempts to perform an action that requires a network connection, the service worker will wait until a network connection has been established to perform the aforementioned action.

A very important thing to note about service workers: they run on a separate thread in a client’s browser than the one that runs your app. After all, JavaScript is a single threaded language with one stack and one memory heap. If the service worker and your app run on the same thread, it’ll lead to many different issues.. but that may be a topic for another post. The reason we point this out is to make note of the context it runs in. It does not have access to the DOM like your app does. However, this also means that it can continue to run in the background even when the web page has been closed.

Why do we need service workers?

Now that you have a good idea of what service workers are and what they can do, let’s talk about why we would use a service worker. Service workers are vitally important for progressive web apps (PWAs) and enable a variety of capabilities. Here are some key ones I would like to point out:

  • It can cache pages. This is important because it allows users to use our app even when they do not have a network connection. It does this by serving files from the cache, when the user is offline, rather than trying to retrieve the assets from our remote server.

How do we use a service worker?

Now that we know the benefits of service workers, let’s talk about how to use one. First, we must know the lifecycle of a service worker. The three main phases are registration, installation, and activation.

Registration:

A service worker must be created in a separate JavaScript file and registered as a background process. Inside the service worker’s JavaScript file, we will define the events it should respond to. For example:

A code example of a service worker listening for fetch events and responding

It is best to create the service worker in the root directory of your app, so it will have access to all the files in your site. This is known as the scope of the service worker. It determines the pages that the service worker can interact with. A service worker can only work with resources in the same directory as itself, and the sub-directories of that location. After a service worker has been created, you must install the service worker into the browser. This will trigger the install event. Here’s an example below:

A code example of how to register a service worker

Installation

Once a service worker has been registered, we now move on to the installation phase. Here, the service worker is downloaded and the browser will try to install it. Once successfully installed, the install event is fired off. As a result, we can add an event listener here for the install event, and perform tasks like storing our static assets in the cache.

A code example of how to open and add assets to a cache upon installation

Last in the lifecycle of a service worker is the activate phase. During this phase, our service worker will activate and run with the worker context (because we registered it as a service worker earlier). This means it will operate on separate thread than your app. Activating the service worker triggers the active event, and will also us to do things like clean up caches from previous service workers. It is important to note that the service worker will only be activate if there is no other active service worker.

Similar to how the install phase triggered the install event, the activate phase triggers the activate event. This allows us to do things such as clearing out the old cache from a previous service worker. Once this has been triggered, the service worker has been activated and will start listening for events and respond as needed, based on what we defined in the service worker file (see fetch code example above, if needed). Now, we have our service worker up and running!

Summary

Service workers are critical to providing key capabilities for PWAs. They do many things like caching assets, enabling background data sync, enhancing app performance by serving cached assets, and enabling offline behavior. Setting one up can be fairly quick (as demonstrated above) and there are many templates out there with service workers set up already. Because of the existence of service workers, we enable our apps to do things that are not dependent on a web page, user interaction, or even a network connection. This opens up a world of possibilities!

Fullstack Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store