images
17th July, 2019

Introduction to Service Worker

Service Worker is a script that executes in the background without interfering with the user interaction, in a separate thread from the browser UI. Service Worker provides rich offline-first user experience, background sync, and push-notifications as well. A website can function offline using a service worker cache.

Service Workers called a game-changer for the web. This the key technology or modern web API behind Progressive Web Applications. Without a service worker, a website is just a website. Service A worker operates as an event-driven system. Service worker goes to sleep to preserve memory when it is not needed. So, data is not saved in the global state in onfetch & onmessage handlers.

How Do Service Workers Work?

A Service worker sits between the browser and the network, acting as a proxy server, handling a collection of non-UI tasks. They are event-driven and live outside the browser process. The service worker is a script that executes in a thread, separate from the UI. This enables the service worker to perform non-UI tasks, making a website perform better.

 

Service Worker Life Cycle

3 steps in its lifecycle:

·        Registration

·        Installation

·        Activation 

Register A service worker

To install a service worker, we need to register it in our main JavaScript code. Registration tells the browser where our service worker is located, and to start installing it in the background.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.
register('/sw.js')
  .
then(function(registration) {
    console.log(
'Registration successful, scope is:', registration.scope);
  })
  .
catch(function(error) {
    console.log(
'Service worker registration failed, error:', error);
  });
}

This code checks to see if the service worker API is available, and if it is, the service worker at /sw.js is registered once the page is loaded.

 

Install a service worker

Once the browser registers a service worker, installation can be attempted. A service worker installation triggers an install event in the installing service worker. 

sw.js
// Listen for install event, set callback
self.addEventListener('install', function(event) {
   
// Perform some task
});

 

Activation

 Once a service worker has successfully installed then the activation stage takes place. If there are any open pages controlled by the previous service worker, the new service worker enters a waiting state. The new service worker only activates when there are no longer any pages loaded that are still using the old service worker.

sw.js
self.addEventListener('activate', function(event) {
 
// Perform some task
});

Once activated, the service worker controls all pages that load within its scope and starts listening for events from those pages.

 

Conclusion

We can do notification management, background sync, and cache with the Service Worker API and some third-party APIs like Cache API. Also, we can develop a Progressive Web App that is fast and user-friendly with Service Worker API like mobile applications.