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!
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.
The service worker lifecycle consists of mainly 3 phases, which are: Registration. Installation. Activation.
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.
unregister() The unregister() method of the ServiceWorkerRegistration interface unregisters the service worker registration and returns a Promise .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With