Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the proper steps for changing or swapping out Service Workers in Production?

I have a PWA built in Angular that is in production and is using the sw-precache service worker. This was before Angular had the @angular/pwa package. If I wanted to switch over and start using the Angular sw instead how would I go about doing this?

Programmatically I would need to handle this for the users. I would think I need to get registered SWs, check for the name of the old SW, unregister it, (purge cache?), and then register the new one. Is it that simple? I feel like with service workers and dealing with caches there's going to be some gotchas. I have yet to find an actual example of this process however.

Any code examples would be much appreciated. Thanks!

like image 824
askilondz Avatar asked Jan 17 '20 15:01

askilondz


People also ask

How do I update my service worker?

update() The update() method of the ServiceWorkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker.

What are the life cycle stages of a service worker?

The service worker lifecycle consists of mainly 3 phases, which are: Registration. Installation. Activation.

How do you by pass the service worker for a particular request?

To bypass the service worker, set ngsw-bypass as a request header, or as a query parameter. The value of the header or query parameter is ignored and can be empty or omitted.

How do I unregister a service worker?

unregister() The unregister() method of the ServiceWorkerRegistration interface unregisters the service worker registration and returns a Promise .


1 Answers

Basically you need to make sure that you "de-register" the old service-worker. If you add @angular/pwa through the schematics, they also create a file called safety-worker.js for you, which in their documentation is used for exactly that purpose: when you want to remove an old SW, you can use that file by simply renaming safety-worker.js to whatever your sw-precache worker's name was. This file could also include instructions for removing the old cache (which you'd need to add yourself). The documentation for the safety-worker can be found in the official documentation.

You can already update the manifest file with the new reference to ngsw-worker.js, since after removal of the old SW, when the page is next visited, the new SW will be installed and take over on subsequent visits.

like image 107
evilstiefel Avatar answered Oct 13 '22 01:10

evilstiefel