PWA - Service Worker Lifecycle made easy - 3 simple steps
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-05-24 18:11:38

## 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](https://dev-to-uploads.s3.amazonaws.com/i/d8jevu8w2lmeo4j8294t.png)

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 )
```javascript
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
    })
}
```

_An example where we mention the scope:_

**app.js** ( or any JavaScript file linked to the webpage )
```javascript
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
    })
}
```

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 )
```javascript
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);
        })
      );
});
```

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**
```javascript
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);
        })
      );
});
```

### 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

{% link https://dev.to/tharunshiv/pwa-why-should-you-use-it-and-not-use-it-447 %}

### Build your own PWA

{% link https://dev.to/tharunshiv/convert-any-website-into-a-pwa-in-just-3-simple-steps-35pp %}

Written by,
{% user developertharun %}

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

![Tharun Shiv](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtxq6bdms36fmn62450h.png)