This content originally appeared on bitsofcode and was authored by Ire Aderinokun
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.
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.
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
);
});
This content originally appeared on bitsofcode and was authored by Ire Aderinokun
Ire Aderinokun | Sciencx (2019-01-29T00:00:00+00:00) What self.skipWaiting() does to the service worker lifecycle. Retrieved from https://www.scien.cx/2019/01/29/what-self-skipwaiting-does-to-the-service-worker-lifecycle-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.