Explaining the lifecycle of Service Workers in PWAs and how to update them as fast as possible.
The Service Worker lifecycle is arguably the most complex part around Service Workers and Progressive Web Apps (PWAs). I only felt like I understood it completely while writing this article, and I hope it will make your life with Service Workers a lot easier.
In this article, I’ll explain the different states that the lifecycle has and what you need to know about them. Afterward, we’ll see how we can update Service Workers in a fast and easy way (using skipWaiting and clients.claim).
Service Workers provide the core-features of Progressive Web Apps. They are similar to Web Workers but extend their capabilities by being able to intercept network requests or delivering push messages. Just like Web Workers, they also run on a separate thread from the browser.
For this tutorial you can think of a Service Worker like a proxy between the network and the browser.
The states of the Service Worker are:
In my mental model, I separate transitional states from regular states. Transitional states transition between two regular states (like Installing and Activate) of the lifecycle and can be accessed by adding a listener to the Service Worker code (e.g. self.addEventListener('install', handler
).
Regular states can be accessed through the registration object like this:
navigator.serviceWorker.ready.then((registration) => {
console.log(registration.waiting); // "waiting" or any other state
});
We’ll see how to do this for each state in the next steps.
#pwa #web-development #programming #developer