The Service Worker life cycle

The life cycle for a Service Worker is pretty simple. There are three main stages:

  • Registration
  • Installation
  • Activation

Each of these stages are pretty self-explanatory.

Registration is the process of letting the browser know where the Service Worker is located and how to install it into the background. The code for registration may look something like this:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered!');
})
.catch(error => {
console.log('Error registering service worker! Error is:', error);
});
}

Installation is the process that happens after the Service Worker has been registered, and only happens if the Service Worker either hasn't already been installed, or the Service Worker has changed since the last time.

In a service-worker.js file, you'd add something like this to be able to listen to this event:

self.addEventListener('install', event => {
// Do something after install
});

Finally, Activation is the step that happens after all of the other steps have completed. The Service Worker has been registered and then installed, so now it's time for the service worker to start doing its thing:

self.addEventListener('activate', event => {
// Do something upon activation
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.82.167