Understanding Service Workers and Caching Strategies

February 12, 2019 0 Comments

Understanding Service Workers and Caching Strategies



If you have been in the javascript or development world for some time, you must have heard about Service Workers. So what are they? In simple and plain words, it’s a script that browser runs in the background and has whatsoever no relation with web pages or the DOM, and provide out of the box features. Some of these features are proxying network requests, push notifications and background sync. Service workers ensure that the user has a rich offline experience.

You can think of the service worker as someone who sits between the client and server and all the requests that are made to the server pass through the service worker. Basically, a middle man. Since all the request pass through the service worker, it is capable to intercept these requests on the fly.

Service Worker as the middle man👷‍♂️

Service workers are like Javascript workers and have no interaction with the DOM or web pages. They run on a different thread and can access the DOM through the postMessage API. If you are planning on building, progressive web apps then you should possess a good understanding of the service workers and the caching strategies.

Note- Service workers are not web workers. Web workers are scripts that run on a different thread to perform load intensive calculations so that the main event loop is not blocked and does not cause a slow UI.

To use service worker in a site we must first register a service worker in one of our javascript files.

In the above code, we first check if the service worker API exists or not. If the support exists, we’ll register the service worker, using the register method by providing the path of the service worker file. So once the page is loaded, your service worker is registered.

The life cycle of service worker 👀

When the service worker is registered, an install event is fired. We can listen for this event in the sw.js file. Before moving into the code, let’s first understand what we should do in this install event.

  • We would like to set up our cache in this event.
  • Add all the static assets into the cache.

The event.waitUntil() method takes a promise and uses it to know how long installation takes, and whether it succeeded or not. If any single file is not cached, then the service worker is not installed. So, it is important to make sure that there is not a long list of URLs to cache because if even a single url fails to cache, it will halt the installation of the service worker.

Install Stage

Once a new Service Worker has been installed and a previous version isn’t being used, the new one activates, and we get an activate event. In this event, we can remove or delete the old existing cache. The below-given code snippet is taken from the service worker guide.

Activate Stage

Not much to talk about this stage, after the activate stage the service worker sits idle and does nothing until another event is fired.

Whenever a fetch request is made, a fetch event is fired. In this event, we try to implement caching strategies. As I mentioned before, the service worker works as a middle man, all the requests go through the service workers. From here on we can decide whether we want that request to go to the network or to the cache. Below is an example, where the request is intercepted by the service worker and the request is made to the cache if the cache doesn’t return a valid response then the request is fired to the network.

Fetch Stage

The above-shown code is one of the examples of caching strategies. Hope, you have understood about the service workers. Now, we’ll dive into some of the caching strategies.

In the above fetch event, we discussed one of the caching strategies called cache falling back to network. One thing to remember is that all the caching strategies are to be implemented in the fetch event. Let’s get into some of the caching strategies -

Easiest among the others. As you can guess by the name itself, it means all the requests go to the cache.

When to use- Should be used when you want to access only your static assets.

Cache only

The client makes the request, the service worker intercepts it and makes the request to the network. No-brainer !!

When to use- When things that have no offline equivalent, such as analytics pings, non-GET requests.

Network only
Note- This will also work if we don’t use the respondWith method.

It is the one discussed before in the fetch event, service worker makes a request to the cache if the request is not successful it goes to the network.

When to use- If you are building offline first app

Cache falling back to network

First, the service worker will make a request to the network, if the request is successful then great else fallback to cache.

When to use- When you are building something that changes very often like a post page or a game leader board. When your priority is the latest data, this strategy is the go-to.

Network falling back to cache

When both the requests fail, one to the cache and other to the network, you display a generic fallback so that your users won’t experience a blank screen or some weird error.

Generic Fallback

We have covered the most used and basic caching strategies required while developing a progressive web app. There is more to it and you can look it up at The offline cookbook by Jake Archibald.

In this article, we learned about some cool stuff related to Service Workers and Caching Strategies. Hope you liked this article, and if you did, clap your 💖 out and follow me for more content. Thanks for reading 🙏 Please feel free to comment and ask anything.

Tag cloud