Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the name of a service worker?

I'm trying to figure out what happens if I have a service worker registered on a live site called sw.js and then I rename the service worker to service-worker.js. Now the old one isn't found but it is still showing the old cached version.

How long does it take for it to register the new renamed service worker or how does this work at all?

Edit

This is how I have register the service worker in a react application:

componentDidMount() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker
      .register("/service-worker.js")
      .then(registration => {
        console.log("service worker registration successful: ", registration);
      })
      .catch(err => {
        console.warn("service worker registration failed", err.message);
      });
  }
}
like image 354
Johhan Santana Avatar asked Mar 06 '23 14:03

Johhan Santana


1 Answers

The newly created service worker (renamed) cannot take over the old one because the old one is still active and controlling the client. the new service worker(renamed one) will wait until the existing worker is controlling zero clients.

Now imagine a service worker sw.js installed and active (controlling the client), Chrome will visualize the process for you like this

1. The service worker is registered and active

enter image description here


2. Now let's rename the service worker file to sw2.js

enter image description here

You can see that chrome is telling you that something has changed about the service worker. but the current one will keep controlling the client until you force the new one to take control by clicking on the skipWaitting button or by flushing your cache. clicking on the button will cause the sw2.js to take controll over the sw1.js

Now if you need to do this programmatically, you can do it in the install event inside your service worker by calling self.skipWaiting().

self.addEventListener('install', (e) => {

  let cache = caches.open(cacheName).then((c) => {
    c.addAll([
      // my files
    ]);
  });

  self.skipWaiting();
  e.waitUntil(cache);
});

The following animated image from Jake Archibald's article The Service Worker Lifecycle can make the idea more clear.

like image 81
Hyyan Abo Fakher Avatar answered Mar 08 '23 04:03

Hyyan Abo Fakher