Service Worker Lifecycle

Swapnil Ramdas Chavan
Walmart Global Tech Blog
4 min readNov 30, 2020
Service Worker is symbolized with Gear (Source: https://www.deviantart.com )

Don’t get scared looking at the gear GIF. This is not a mechanical engineering related blog. Trust me this blog is a Software Engineering blog.

The motto of this blog series

What is a Service Worker?

It is the JavaScript program that can be used in your Web Application to enable it to serve customer requests when they are offline and provide various features for making your web application a Progressive Web App.

For a better understanding of Service Workers please read this blog.

In this blog, we are going to discuss the Lifecycle of Service Worker.

THE Lifecycle

Register Service Worker Script

To initiate the Service Worker lifecycle, we first need to register our service worker script (serviceWorker.js) in the JavaScript(main.js) which is linked to the landing page(index.html) of your application.

The below-given code is to check if ServiceWorker API is available in your browser. If the API is available, we can register our service-worker script.

Code that Registers your Service Worker script
Service Worker Lifecycle (Source: https://developers.google.com/web/fundamentals/primers/service-workers)

Install Event

This is the first event the Service Worker gets and is called once per service worker. It means, once a new or updated service worker is registered, it will be treated as a new service worker and it will get its own Install event.
In the Install step, we can cache the static assets. Static files such as media assets (images, audio files), CSS files, static HTML pages can be cached after creating cache storage. This step is essential as the requests made being offline will be intercepted by the service worker and served with the files cached during this event.

Code for Install Event

In the Install event, we pass a promise to event.waitUntil(). We can log the messages corresponding to caching and Install event completion. The cache is created with open(cacheName) and the files are added to the cache with cache.addAll(cacheAssets).

Activate Event

After the Install event, the Activate Event must be called to have the Service Worker intercept the requests from that point of time. The current page which registers the service worker script won’t be controlled by the Service Worker installed. We need to reload the page to get it under the service worker’s control.
Activate event, is the place where we can manage the cache created by the old service workers. We can delete the previous caches created by older versions of Service Worker.
NOTE: Creating new caches for every script update is generally done by developers. So we need to change the name of our cache for every service worker script update.

Code for Activate Event

We pass a promise here to event.waitUntil() which performs cache management. In the above code, if any cache with name other than current cacheName exists, it will be deleted.

After the Activate event, the Service Worker will control all the pages that fall under its scope. The Service Worker will handle “fetch” and “message” events if the site is loaded being offline. If the connection is idle, the requests would be served by the server, and Service Worker will be terminated.

Handle Fetch Event by Serving file from Cache

Scope of Service Worker

The default scope of our service worker is ./ relative to the service worker script URL. It means, if your script is in the root directory, the scope will be all the files in the root directory, the packages of the root directory, and all files under these packages.
The fetch request for pages outside the scope won’t be intercepted by Service Worker. So, we should place the Service Worker script at the location in the directory, under which most of the pages that must be available offline exist.

Service Worker Update

If there are any changes in the service worker script, the next time when the user is connected to your site, the browser will re-download the script in the background. It will be launched alongside the existing one and will get its own Install event.
If the old service worker is controlling the pages, the new service worker will enter a waiting state. After the Install event is successful, the new Service Worker won’t get an Activate event until it gets complete control over the clients (i.e. the old service worker is no longer serving any client requests). If all the loaded pages are closed, the old service worker is killed and the new worker takes control. This is when the new service worker gets the Activate event.

To avoid the waiting state, we can call self.skipWaiting()in the Install event. So, the new service worker activates as soon as it's finished installing.

Conclusion

It is very important to have an understanding of the Service Worker Lifecycle. It helps us decide the right place where the code for caching and cache management must be executed. Service Workers are really useful to serve customer requests when they are offline. It also offers various other features such as Push Notification and Background Sync which can help the web developers give their customers a rich offline experience.

What’s Next?

After having an understanding of the Lifecycle, we should see an example of the implementation of the Service Worker. The next blog of this series gives a demo on Service Worker. It will help you get a better idea of the useful features of Service Worker and how to implement those in your web application. Hope you find it helpful 🙂.

--

--