What is Service Worker?

Service worker helps the user to browse offline using cache. They also offer advantages of push notifications, background sync, and deep platform integration.

Service Worker act as a proxy between the internet and application. It runs in the background of an application to intercept network requests and cache information.

There are 4 main technical components of a Progressive Web Application (PWA) – Service Workers, Web App Manifest, Web Icon and HTTPS. These are explained in detail below:-

  1. Service Workers- They help in downloading data offline and perform fetch and install tasks. 
  2. Web App Manifest- It is JSON file that provides meta-information about the PWA. It has information such as web app icon, its name, and background colour, etc.  
  3. Web Icon- Your site is going to be on the home screen, you need some sort of icon to represent it. Here I’ve used a downloaded logo from the internet.
  4. Https- In order to have a progressive web app, it must be served over a secure network. This is not only a best practice but also ensures reliability and avoid middleman attacks.

Why Service Workers are Awesome?

You can become the king of Network Traffic!

Manage all your web traffic and do any type of changes you want. For example, When the webpage requests to a CSS file on a slow internet connection, then you can send plain text as a response.

Similarly, you can send png file in response to HTML request. It all depends on the network traffic and connection.

Cache any response

You can access webpage content even when you are offline using cache requests with service workers.

Push notifications

Send notifications to the user even when they are offline or not browsing the website using Service Workers.

Do not disturb

Even if the Internet connection is weak, then also you can commence any process with Background sync opportunity offered by Service Worker.

What Service Workers can’t do?

There is always scope for Improvement. There are some actions that service workers cannot perform such as:-

You cannot change DOM elements

Service workers cannot directly interact with the webpage or access the DOM because it runs on a different thread. But, you can communicate to the window via post message.

It doesn’t work on 80 Port

It function on HTTPS protocol. But it can function on localhost during development.

How do Service Workers Work?

A service worker is present between the browser and the network. It acts like a proxy server and deals with a collection of non-UI centric tasks. They are driven by events and hence, can work without an active browser. Run on a different thread than UI. This helps in improving the functionality of a website. 

Service workers stop when they are not in use and begin when needed, this helps in reducing strain on CPU and battery drainage. They work offline by caching API and intercepting all the network requests. It not only helps in having an offline experience but also fast loading of a website. 

What are the prerequisites for Service Workers?

Service Worker requires HTTPS protocol to function. But it can also work on localhost during development.

What browsers support Service Workers?

Majority of the browsers now support Service Workers with the exception of Internet Explorer (IE). If you want to know which browsers support Service Workers in detail, then you can visit IsServiceWorkerReady.

Service Worker v/s Web Worker

  1. Service workers and Web workers are JavaScript workers. But they have differences too. 
  2. They help in offline browsing, push notifications and background synchronization. All the communication is done via post message method. 
  3. Web workers allow complex tasks to run in the background and keeping the UI Jank free. All the communication is done via service workers post message method. 

Service Worker v/s Appcache

  1. Service workers are low-level event-driven API in comparison to AppCache which is a  high-level event-driven API. 
  2. WIth AppCache you have to state which resources you want your browser to cache. 
  3. In case of Service workers, you have to write a script to fetch events and cache their responses. 
  4. So, you can say that Service workers are new and improved version of Appcache. 

Service Worker Lifecycle

Service Worker lifecycle has 3 steps; Registration, Installation, and Activation.

Registration-

To install a service worker, you have to register it in your background page. It informs the browser regarding the location of service worker in JavaScript file.

You can use the following code to check if the Service Worker API is available or not. If it is there, then service worker /sw.js is registered when the page is loaded. 

// app.js

if (‘serviceWorker’ in navigator) {

    navigator.serviceWorker.register(‘/sw.js’)

    .then(function (registration) {

        console.log(‘Service worker registered!’);

    })

    .catch(function (err) {

        console.log(‘Registration failed!’);

    })

}

We can also define the scope of service worker while registering it. It determines the number of pages that the service worker can control. By default, the location of service worker defines its scope and control.

For example, in the following code we have defined the scope of service worker to /blog/. This means that its use is limited to only blog directory. 

// app.js

if (‘serviceWorker’ in navigator) {

    navigator.serviceWorker.register(‘/sw.js’, {

        scope: ‘/blog/’

    })

    .then(function (registration) {

        console.log(‘Service worker registered!’);

    })

    .catch(function (err) {

        console.log(‘Registration failed!’);

    })

}

Installation (Install Event)

After the successful completion of the registration process, the service worker script is downloaded and the installation event is initiated.

The service worker will only be installed if it hasn’t been registered before or if it’s script gets altered even by 1 byte. 

You can define a callback for the install event and decide which files to cache.

Following is the example of installing Cache API event:-

// sw.js

const assetsToCache = [

    ‘/index.html’,

    ‘/about.html’,

    ‘/css/app.css’,

    ‘/js/app.js’,

]

self.addEventListener(‘install’, function (event) {

    event.waitUntil(

        caches.open(‘staticAssetsCache’).then(function (cache) {

              return cache.addAll(assetsToCache);

        })

      );

});

You need to take the following steps to install an event:-

  1. Open a cache.
  2. Cache your files.
  3. Confirm if all the required assets are cached or not.

If all the files are successfully cached, then you can say it is successfully installed. If any of the above files fail to download, then the step of installation will fail. 

Activation

After successful installation, service worker enters an installed state. It is not active yet but takes control of the page from the current service worker. 

A service worker doesn’t get active immediately after installation. It can be activated if no other service worker is currently active, user refreshes the page or if the self.skipWaiting () is called the script of installed service worker. 

This can be further understood with the following example:-

/ sw.js

self.addEventListener(‘install’, function (event) {

    self.skipWaiting();

    event.waitUntil(

           // static assets caching

      );

});

If the service worker is active, an Activate event is fired up. You can check it by performing some specific tasks such as clearing out cache.

Following is an example of activating an event- cache delete in which it deletes all the existing cache.

// sw.js

const cacheVersion = ‘v1’;

self.addEventListener(‘activate’, function (event) { 

    event.waitUntil( 

        caches.keys().then(function (cacheNames) {

            cacheNames.map(function (cacheName) {

                if (cacheName.indexOf(cacheVersion) < 0) { 

                    return caches.delete(cacheName);

                   } 

                }); 

            });

        }) 

    ); 

});

Once the service worker has been activated, it now has full control of the pages. After activation of service worker, you can handle events such as fetch, push and sync.

What are the key benefits of PWA?

So far we have discussed what is service worker? Now, it’s time to move onto its key advantages. Given below are 6 features of PWA that make it better than non-progressive web applications:

  1. Quick Installation- Unlike native apps, you can download PWA VERY FAST AND QUICK. In the majority of cases, it takes 2-3 seconds to download and install progressive web apps. You just have to go to the website in the browser and click on the “Add to Home Screen” button. Phew! It’s done.
  2. Extremely fast- TIME IS MONEY. PWAs are very fast and run seamlessly even without hitting the network. Therefore, saving your time and money.
  3. Reliable- Imagine you have to board a flight and need your boarding pass quickly. But, the network connectivity is really bad. What will you do? Nothing. Just go to your air ticket booking web app and download boarding pass instantly. That is the level of reliability it provides.
  4. Integrated user experience- The main purpose of the introduction of PWA was to ensure that users should not know if they are on a website or an app. It is present on a user’s home screen and has access to a device’s functionalities like native apps. 
  5. Engagement- Web apps are very helpful in boosting user-engagement by keeping the user notified and updated. Pushing notifications even when it is closed can bring the user back.
  6. Responsive- One of the most important benefits of the web app is its responsive design. It generally fits in all the different sizes of devices. 

What are Progressive Web Apps Examples?

There are many popular companies that use PWA. Some of the examples are given below:-

  1. Alibaba
  2. Lancome
  3. Flipkart
  4. OLX
  5. Twitter
  6. Instagram

Free Tools to Check if your website has PWA app or not

You can check if your website has a PWA app or not using the following tools:-

  1. Lighthouse
  2. Lambda Test
  3. Chrome Developer Tools

 

Was this post helpful?

Share This