Search code examples
angularservice-workerangular8progressive-web-appsangular-service-worker

Trigger event when serviceworker finished fetching new files?


Short: I wonder whether it is possible to trigger some kind of event or callback when the serviceworker finished downloading files after an update.

Long version: I have a PWA using angular(8) and its angular serviceworker. In the ngsw config I put the install and update mode to prefetch.

Normally when an update is pushed to the server, the application registers to the update event and the serviceworker starts downloading the new files (.js, assets, .html etc). I can see in the network tab of the console how the new files are downloaded one by one. However since it is a large app, this can take several minutes.

Since my PWA is used a lot in offline mode, it is fatal if the update was not completed before the user closed the app or lost internet connection, because he might miss some scripts or pages. I would like to tell the user, when files are still downloading or at least when the file download has completed.

Is there some kind of callback, hook or whatever that gets triggered when the serviceworker finishes downloading stuff? Or maybe some other form to acchieve this?


Solution

  • Yes, Angular provides a SwUpdate service you can subscribe to. It's usage looks like this:

    @Injectable()
    export class LogUpdateService {
    
      constructor(updates: SwUpdate) {
        updates.available.subscribe(event => {
          console.log('current version is', event.current);
          console.log('available version is', event.available);
        });
        updates.activated.subscribe(event => {
          console.log('old version was', event.previous);
          console.log('new version is', event.current);
        });
      }
    }