Hello folks!! In this article, we'll learn about service workers and their role in creating progressive web apps.
A service worker is a script that runs in the background of a web page, separate from the main page thread.
Service workers are background process. Their job is to provide an app-like functionality by listening and reacting to the events which occur in the browser.
Service worker listens to events such as fetch HTTP requests made by the browser.
Service Worker follows the following lifecycle:
Install: After the registration, the browser downloads and installs the service worker script. We can listen to this lifecycle event inside the
sw.js\file itself. This event is fired only once when the service worker is registered. Or the code inside the service worker file has changed since the last time it was installed in the browser.
Active: When the service worker is installed it becomes active. Once the service worker is active, it can access all the different pages and all the different files inside its scope.
If we made some changes in the service worker file then it will become active only when all the instances of our app are closed.
Fetch and Cache: When a fetch event occurs, the service worker intercepts the network request and can respond with cached assets instead of making a network request. This allows the service worker to serve content even when the user is offline. The service worker can also update the cache with fresh content from the network when available.
Update: When a new version of the service worker is detected by the browser, it is downloaded and installed in the background. The new version enters a "waiting" state while the currently active service worker handles any ongoing events. Once all tabs using the old service worker are closed, the new version takes control during the activation phase, and the cycle continues.
Service workers help to achieve all the things that you would expect in a modern app that runs on a mobile device like:
Load Content Offline: you still open and view the app without any internet connection by using cached assets and data.
Use Background Sync: If a user tries to perform an action while they're offline that normally requires a connection, then it will perform an action in the background when a connection is re-established.
Use Push Notifications: Our app can notify users on a device