Experiencing the service worker life cycle
The first event that a service worker experiences is the 'install'
event. This is when a user first starts up a PWA. The standard user will only experience this once.
To tap into this event, all we have to do is add an event listener to our service worker itself. To do that from within sw.js
, we use the self
keyword:
self.addEventListener('install', function() { console.log('Install!'); });
When you reload the page, you should see 'Install!'
appear in the console. In fact, you should see it every time you reload the page, unless you uncheck the Update on reload
option under Application
| Service
Workers
. Then, you will only see it the first time.
Next up is the activate
event. This event is triggered when the service worker first registers, before the registration completes. In other words, it should occur under the same situations as install, only later:
self.addEventListener('activate', function() { console.log('Activate!'); });
The last event we...