Angular with Service Worker doesn't update website when user renavigates to the website

1.6k Views Asked by At

I have an angular application and I'm trying to setup software updates with the ServiceWorker module.

I've got things setup so that if a user is presently on the website and if I push out a new version of my website then the next time I do this.swUpdate.checkForUpdate() it will detect a new version of the website is available. (this is setup to check every 30 minutes)

My issue is that when a person (who had previously visited my website) comes to my website after an update was pushed (say I deploy today in the morning and the user navigates to the website this evening) then they will see the old website for about half a minute then the website will detect a new updated website. At which point I display a message that they should update/reload the website.

I'd like it so whenever a user comes to my site that they grab a fresh current website.

... I'm just imagining that, as it is currently, I can see a person who is an infrequent user getting annoyed that every time they come to my site they're instructed to update the website.

Here's how I register the service worker in app.module.ts

enter image description here

Here's how I check for updates (currently checking every 30 minutes)

enter image description here

1

There are 1 best solutions below

0
On

There is another event you should look for which is the 'VERSION_DETECTED', then call this.swUpdate.activateUpdate(). This method will trigger the 'VERSION_READY' event when done. An exemple of my implementation :

this.swUpdate.versionUpdates.pipe(
                tap(update => {
                    if (update.type === 'VERSION_DETECTED') {
                        // activateUpdate() will trigger the 'VERSION_READY' or 'VERSION_INSTALLATION_FAILED' event when done
                        console.log('New server version detected, trying to install...');
                        this.swUpdate.activateUpdate().then();
                    }
                    if (update.type === 'VERSION_READY') {
                        // this._reloadPage will be set to true, asking a full page reload on next navigation
                        console.log('New server version installed');
                        this.notify(false);
                    }
                    if (update.type === 'VERSION_INSTALLATION_FAILED') {
                        // this._clearCacheAndReload will be set to true, asking a cache clear and full page reload on next navigation
                        console.warn('Error while installing update, cache will be cleared and page reloaded');
                        this.notify(true);
                    }
                    // another event type possible is 'NO_NEW_VERSION_DETECTED', we don't need to handle it
                })
            ).subscribe();