A service worker goes through register, install, waiting, activate and then handles fetches. A new version waits so that an open page is never served by two different versions.
The steps:
- Register: the page calls
navigator.serviceWorker.register("/sw.js"). The browser downloads the script. - Install: the browser fires
install. Here the worker usually pre-caches core assets withevent.waitUntil. If it is the first service worker, it activates next. - Waiting: if an older version already controls open tabs, the new one installs and then waits.
- Activate: on
activate, the worker usually deletes old caches. - Fetch: after that, it receives
fetchevents for pages in its scope.
Why the wait? The new version only activates once every tab using the old version is closed. This way, a page never has two versions of the worker serving it during one visit.
A simple reload does not activate a waiting worker. During a reload, the old page is still open while the new one loads. So the old version never stops controlling the tab. You must close all the tabs, or use the methods below.
self.skipWaiting() makes a new worker activate without waiting. clients.claim() makes it take control of pages that are already open. Use them carefully. Old pages may then talk to a worker that serves different assets.
- The lifecycle is register, install, waiting, activate, then fetch.
- Pre-cache files in
install, and clean old caches inactivate. - A new version waits until all tabs using the old version close.
- A simple reload does not activate a waiting service worker.
skipWaiting()andclients.claim()skip the wait.