DEV Community

Cover image for PWA - Service Worker Lifecycle made easy - 3 simple steps
Tharun Shiv
Tharun Shiv

Posted on • Edited on

PWA - Service Worker Lifecycle made easy - 3 simple steps

What is a Progressive Web App?

Progressive Web Apps ( PWA ) lets you create websites with Native Apps like experience and features. These features include:

  • A mobile app-like experience
  • Offline capabilities
  • Push Notifications
  • Background Sync and more All of these can be created with the same technology that you use to build your websites. Yes, JavaScript I mean.

Service Workers

A key player in this PWA universe is the "Service Worker". The service worker is a JavaScript File that runs on a separate thread apart from the one in which your usual website JavaScript files run. The service worker is always up, and is listening to the incoming responses and the outgoing requests.

SW Thread

It doesn't have the ability to modify the DOM of the website but can do a lot of powerful tasks like

  • handling push notifications
  • background sync
  • intercepting requests and responses
  • caching the files to enable offline experience and more

3 Phases of LifeCycle

For the Service worker to start performing its background tasks, we have to make sure it is up and running in the background. The phases through which the Service Worker goes through can be broadly classified into:

  1. Registration Phase
  2. Installation Phase
  3. Activation Phase

1. Registration

The first phase in the service worker's lifecycle is registering it to the browser. The registration can be done in two different ways:

  • You either specify a scope for the service worker
  • You leave it to the default global scope of where the service worker file is present

Scope means the files to which the service worker has access to.

Let us look at the below example to register a service worker:

app.js ( or any JavaScript file linked to the webpage )

if ('serviceWorker' in navigator) { // check compatability 
    navigator.serviceWorker.register('/sw.js') // register
    .then((res) => {
        console.log('Service worker registered!'); // success
    })
    .catch((err) => {
        console.log('Registration failed!'); // failure
    })
}
Enter fullscreen mode Exit fullscreen mode

An example where we mention the scope:

app.js ( or any JavaScript file linked to the webpage )

if ('serviceWorker' in navigator) { // check compatability 
    navigator.serviceWorker.register('/sw.js', {
        scope: '/pages/'
    })
    .then((res) => {
        console.log('Service worker registered!'); // success
    })
    .catch((err) => {
        console.log('Registration failed!'); // failure
    })
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the service worker functions only with the scope of the pages directory.

2. Installation

What we previously did was only registering the service worker with the browser, but not install it. Once the service worker is successfully registered, it is not ready to be installed. The Service worker script is downloaded to the browser and the browser will attempt to install the service worker.

There are a few situations in which the service worker will be installed:

  1. A new service worker file
  2. A modified service worker file

This installation is automatic, and once it is installed, the install event is fired and we can listen to this event to do certain tasks. Say we wanted to have the offline ability, we can cache the assets in this install event.

Example: Caching assets during the install event

sw.js ( different from the registration file )

const cacheName = 'site-cache-v1'
const assetsToCache = [
    '/',
    '/index.html',
    '/css/styles.css',
    '/js/app.js',
]

self.addEventListener('install', ( event ) => {
    event.waitUntil(  
        caches.open(cacheName).then((cache) => {
              return cache.addAll(assetsToCache);
        })
      );
});
Enter fullscreen mode Exit fullscreen mode

In the above example, we first declare the static cache name and the assets to the cache. On the install event, we are waiting until the caching of the files is done. So we open the cache storage and store all of the assets.

3. Activation

Once the installation phase is successful, the next phase is the Activation phase. The service worker is now in the installed state but not yet active. The service worker does not move into the active state immediately after installation automatically! A service worked can move into the activated state only in the below cases:

  • None of the pages use the service worker and are closed
  • There is no other service worker active on that page

There are a few ways to force the activation of the new service worker

  • One can shift+reload and hard refresh the page
  • Close the tab / navigate to another page not handled by the service worker
  • Go to the service worker tab in the developer tools and click on skip waiting.

You can also call the skipWaiting() method during the install event to trigger automatic activation of the service worker.

Example

sw.js

const cacheName = 'site-cache-v1'
const assetsToCache = [
    '/',
    '/index.html',
    '/css/styles.css',
    '/js/app.js',
]

self.addEventListener('install', ( event ) => {

    self.skipWaiting(); // skip waiting

    event.waitUntil(  
        caches.open(cacheName).then((cache) => {
              return cache.addAll(assetsToCache);
        })
      );
});
Enter fullscreen mode Exit fullscreen mode

Other states of the service worker

  1. Idle state - where the service worker does not receive functional events
  2. Terminated state - the service worker goes into this state after being idle for a long time
  3. Unregistered state - the service worker is either replaced by another service worker or unregistered manually.

πŸ™‚If you love web development videos, consider Subscribing to the YouTube channel : https://youtube.com/c/developerTharun πŸ”₯

Hope this article helped you understand about the lifecycle of the Progressive Web Apps. Leave a like ❀, unicorn πŸ¦„ and save the post for later if you liked it. 😊 Comment your opinion or experience in PWA. πŸŽ‰ Follow me if you would like to read such articles. 🎢

Related Articles of mine:

Advantages of PWA

Build your own PWA

Written by,

Thank you for reading, This is Tharun Shiv a.k.a Developer Tharun

Tharun Shiv

Top comments (10)

Collapse
 
praveenreddy1798 profile image
praveenreddy1798

Simple examples, thanksπŸ‘

Collapse
 
developertharun profile image
Tharun Shiv

Glad it helped😊

Collapse
 
venkat121998 profile image
venkat anirudh

I was confused about the service worker lifecycle, but this article nailed it in explaining about them. Thank you. It would be great if you could do a series on PWA, either article or video based series.

Collapse
 
praveenreddy1798 profile image
praveenreddy1798

+1

Collapse
 
developertharun profile image
Tharun Shiv

Thank you praveen

Collapse
 
chandrika56 profile image
Jaya chandrika reddy

Yeah, a series would be helpful.

Collapse
 
developertharun profile image
Tharun Shiv

Thank you ma'am

Collapse
 
developertharun profile image
Tharun Shiv

Thanks a ton Venkat! 😊

Collapse
 
uma_bcc profile image
umamaheswari.v

Great post with illustration and examples. Keep it up πŸ™Œ

Collapse
 
developertharun profile image
Tharun Shiv

Thank you ma'am πŸ™‚