CodePark/ questions / Web workers & service workers
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Web workers & service workers

Describe the service worker lifecycle. Why doesn't a new version take over immediately?

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 with event.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 fetch events 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 in activate.
  • A new version waits until all tabs using the old version close.
  • A simple reload does not activate a waiting service worker.
  • skipWaiting() and clients.claim() skip the wait.