How to register a service worker in JavaScript


A JavaScript service worker is a piece of JavaScript script that runs in the background of your browser, completely separated from the browser, to activate features that don’t require user attention. Service workers are delivering cool services like push notification, loading and syncing data on load. But the best feature, in my opinion, is providing offline experience for WPA.

In order to implement service workers, we need to install a service worker first by registering service worker with your app page. At installation step typically static assets are cached. The trick with caching static stuff is that it will fail if a resource is missing.

After install, you need to clear old cache before activating the service worker. When a service worker is activated it can either be terminated to save browser memory or handle fetch functions.

 

var cacheName = 'weatherPWA-v1';
var filesToCache = [
/*static resources go here*/
];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
});

self.addEventListener('fetch', function(e) {
  console.log('[ServiceWorker] Fetch', e.request.url);
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});

and remember to add the service worker into your app.js

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
     .register('/service-worker.js')
     .then(function() { 
        console.log('Service Worker Registered'); 
      });
  }
Ramin Ahmadi
I am a full-stack front end developer with over 5 years experience in web design and development. I have worked with a wide variety of environments and languages including Angular, TypeScript, NodeJS, Restful API, Microservices, Atomic design, JQuery, Material design, Progressive Web Apps, DevOps, and many Azure tools. I make it a goal to automate myself out of routine tasks in my daily work. My motto is, ‘write human readable code, lean and clean’.

Comments 3

Your email address will not be published. Required fields are marked *

  1. Great beat ! I would like to apprentice while you amend your website, how can i subscribe for a weblog web site? The account aided me a appropriate deal. I had been a little bit acquainted of this your broadcast provided brilliant clear idea

  2. Good day! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks

How to register a service worker in JavaScript

log in

Captcha!

reset password

Back to
log in
Font Resize
Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
List
The Classic Internet Listicles
Image
Photo or GIF
Gif
GIF format