An Introduction to Service Workers in JavaScript

Posted By Mayank Jain | 31-Jul-2018

Service worker is basically a JavaScript file (script) that works in background and assists in offline first web application development. It is a programmable proxy between your web page and the network, providing the ability to intercept and cache network requests. 

Features of Service Workers

  • Cache

We can cache response/request pair with Service Worker and Cache API to access these offline content anytime. We can fetch data when the mobile application is in the background or when our mobile application is closed, so even not running in the background.

  • Push Notifications

We can manage push notifications with Service Worker and show any information message to the user. Service Workers run even when the app is not running so it allows a user to opt-in to timely updates from sites they visit and love and allow you to effectively re-engage them with customized, engaging content.

  • Background Sync

Although the Internet connection is broken, you can start any process with the Background Sync of Service Worker. It provides a delay in the process until the Internet connection has stable.

 

How to Register Service Workers?

 

To install a service worker we need to register it in our page. This informs the browser where your service worker JavaScript file presents. We can register Service Workers on each page load without concern, the browser will handle, if the registration is required or not.

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration successful
      console.log('ServiceWorker registration is successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}
        

 

 Code checks if the service worker API is available, and if it is avaialable, the service worker at /sw.js is registered.

 

Request for Proposal

Recaptcha is required.

Sending message..