DEV Community

Cover image for Everything you want to know about Service Worker
Nishant Contractor
Nishant Contractor

Posted on

Everything you want to know about Service Worker

This blog is all about service worker, how its work, where we can use it, how we can remove that, where it will not work and many more. Will start with the introduction.

Service Worker

Service worker is java script file that runs in user’s browser as background process.

How service worker works

It intercept network requests, caching or retrieving resources from the cache, and delivering push messages.Service workers can be accessed by many tabs in the browser at the same time because only one service worker can Exists per scope and existence is independent from the main thread.

To install Service worker in your project, first you need to register service worker

Register service worker

To register service worker first we need to check if browser supports it or not? using “navigator Object”.navigator Object contains information about the browser.

Your first service worker downloads when you call register() function.

if ('serviceWorker' in navigator) {
   navigator.serviceWorker.register('/ServiceWorker.js')
   .then(function(response) {
      // Service worker registration done
       console.log('Registration Successful', response);
   }, function(error) {
       // Service worker registration failed
       console.log('Registration Failed', error);
})
}

The service worker can only access folders below it, so it is probably best to keep it in the root of the project (the top most folder).
Register function on service worker downloads the service worker script from provided URL and executes it.

In above code response contains information about the state of the service worker as well as it’s scope.

In ServiceWorker.js file we can write code for installation,update, push etc.

If service worker fails to register, the register promise rejects, and the service worker is discarded.

How to add service worker

After Successfully registration of service worker, installation can executes:

Install Service Worker:

If service worker is the new or updated, the installation process will start.At this stage you can cached you static content or file.
This event only trigger if “ServiceWorker.js” doesn’t exists or file is newer version(updated).

self.addEventListener('install', cach => {
 event.waitUntil(
     caches.open('v1').then(cache => {
         return cache.addAll([
           '/favicon.ico',
         ]);
       })
     );
 });

Service Worker not installed if any file failed to catched which is provide in cache.addAll() function.
By using event.waitUntil() service worker not terminate until the promise passed to waitUntil() method is either resolved or rejected.

After successful installation Activation event trigger of service worker

 self.addEventListener('activate', event => {
   console.log('v1 now ready to handle fetches');
 })

How to clear service worker cache

In activation event we can remove or delete existed cached item using cache.delete() method.

For Remove Clear Catch

self.addEventListener('activate', function(event) {
 event.waitUntil(
   caches.keys().then(function(cacheNames) {
     cacheNames.forEach(function(cacheName) {
       caches.delete(cacheName);
     });
   });
 )
}

caches.keys() method provide names od all caches accessible to you.

Everytime user makes request for page, service workers fetch event fires.
In this event we decide whether we want that request to go to the network or present catch items.

self.addEventListener('fetch', event => {
   const url = new URL(event.request.url);
   //serve the image from catch if the request is same origin
   if(url.origin === location.origin) {
    //image which is stored at the time of installation
    //respond with cached 
       event.respondWith(caches.match('/favicon.ico'));
   } 
})

Give respond with netweork call

self.addEventListener('fetch', event => {
     event.respondWith(fetch(event.request));
 })

respondWith() method allows you to promise for a Response yourself.

Update Service Worker

If we make changes in the service worker’s script file then the browser is considered as a new service worker and it’s installed event fire.

When we update service worker, new service worker not control clients because
Old service workers handle client’s. When we close browser the old service will be killed and new one takes place of old service worker.

If we want to use a new service worker as soon as installation is completed we can use the self.skipWaiting() method.
This method activates service workers as it’s finished installing.

If a new service worker fails to install, the old one continues to handle clients(pages).

In development mode Check the checkbox update on reload which is update service worker on page refresh.

Debugging Service Worker

Service workers are only available to "secure origins" (HTTPS sites, basically).

To Inspect service worker from chrome
Goto to developer tool(F12) or right click on page click on inspect tab
Go to application tab and then click on service worker from sidebar
In Sidebar you have list of register service Worker.

How to test service worker on localhost

For developing purposes You can use localhost because localhost is also considered as “secure origins”. Or setup a local server by using npm http-server and serve package.

Unregister Service Worker/ Remove service worker / Disable service worker

For unregister service worker

if ('serviceWorker' in navigator) {
     navigator.serviceWorker.getRegistration().then(
       function(registrations) {
         for(let registration of registrations) {
           registration.unregister();
         }
       }
     )
 }

The service worker may not die immediately. If the worker is currently performing any tasks for a client it will complete before being officially removed.It will only be removed after page reload or closed.

Because of this you can make dummy new service workers and use it in place of currently working service workers.
By Placing unregister() method of service worker in activation event of service worker and force each client’s browser to reload the page.

How To manually unregistered service worker from chrome

Goto to developer tool(F12) or right click on page click on inspect tab
Go to application tab and then click on service worker from sidebar
In service worker you have list of registered service worker
From that you can manually unregister service worker by clicking on the unregister link.

Top comments (2)

Collapse
 
bcdbuddy profile image
Babacar Cisse DIA

thanks for this.
Found typo in article:

  • od all (of all)
  • netweork
Collapse
 
shikha_dev profile image
Shikha

Thanks for sharing this..
After unregistering through application tab.
Application is breaking for me.. is this the excepted behaviour?