29

What self.skipWaiting() does to the service worker lifecycle

 5 years ago
source link: https://www.tuicool.com/articles/hit/rQJ73uB
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The ServiceWorker.skipWaiting() method is a life saver. It ensures that any new versions of a service worker will take over the page and become activated immediately.

To understand why this is so important and useful, we need to revisit the service worker lifecycle. I have a more detailed article about each step of the lifecycle, but you just need to know that there are six states that a service worker can be in - parsed, installing, installed (waiting), activating, activated, and redundant.

jY7B3mr.png!web

When we first try to register a service worker via navigator.serviceWorker.register() , the file passed is parsed and, assuming there are no errors, the service worker is installed. For a page with no previous service worker files, the newly installed service worker becomes activated immediately.

If, however, the page already has an activated service worker file, things are more complicated.

Endless waiting

If the page already has an activated service worker and a new file is pushed, the new file will still be parsed and installed. Once installed, it will wait for an opportunity to become activated.

Without self.skipWaiting() , a waiting service worker will only become active itself once the currently active service worker is released and becomes redundant. This can only happen in two scenarios:

  • If the user has navigated away from the page, thereby releasing the previous active worker
  • If a specified period of time has passed, thereby releasing the previous active worker

So, unlike we are used to when pushing new versions of assets to our website, a new version of a service worker can be waiting for what seems like forever. Even if a user refreshes their page, they may not receive the updated version for a very long time.

self.skipWaiting() to the rescue!

The ServiceWorker.skipWaiting() method solves this problem by telling the newly installed service worker to skip the waiting state and move directly to activating.

biAZfaU.png!web

The self.skipWaiting() method is typically used in the install event of the service worker. As long as the method is called before the waiting phase itself, the service worker will skip the waiting phase and become immediately activated.

service-worker.js

self.addEventListener('install', function (event) {

    self.skipWaiting();

    event.waitUntil(
        // Do stuff
    );
});

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK