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.
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:
- Registration Phase
- Installation Phase
- 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
})
}
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
})
}
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:
- A new service worker file
- 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);
})
);
});
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);
})
);
});
Other states of the service worker
- Idle state - where the service worker does not receive functional events
- Terminated state - the service worker goes into this state after being idle for a long time
- 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
Article No Longer Available
Build your own PWA
Article No Longer Available
Written by,
Top comments (10)
Simple examples, thanks👍
Glad it helped😊
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.
+1
Thank you praveen
Yeah, a series would be helpful.
Thank you ma'am
Thanks a ton Venkat! 😊
Great post with illustration and examples. Keep it up 🙌
Thank you ma'am 🙂