← Concepts

阅读中文版本

Service Worker Lifecycle

The service worker lifecycle installs, waits, and activates per scope, letting new versions take over only when all old clients close, which is why updates appear to lag by a session.

browser

Definition

A service worker is a per-scope script controlling fetches for pages in its scope. Its lifecycle runs registering, installing, waiting while an older worker controls clients, and activating when no old-controlled pages remain. skipWaiting and clients.claim let a new worker seize control early, at the cost of mixed-version clients.

Context and scope

Managed by offline-first apps, update flows, and precaching strategies. Explains why users see the previous release until all tabs close, and how to build update prompts on waiting workers.

Common misconceptions

  • The browser always updates service workers promptly — a new worker waits while old tabs still control pages, delaying activation
  • skipWaiting is a safe convenience — it can mix page assets from the old version with a new worker, breaking lazy-loaded chunks
  • Service workers cache pages automatically — caching happens only through explicit strategies you program

Anti-patterns

  • Deploying breaking SPA changes while the old worker serves stale chunks to a claimed new page
  • Calling skipWaiting on every update without coordinating reloads, stranding hybrid versions in the wild
  • Assuming unregister in devtools fixes users — production workers persist until their update check or expiry runs

Related concepts

Related examples

Authoritative source

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

What it is

One service worker controls a scope, and only one version is active per scope at a time. When you deploy an update, the byte-different script triggers install of a new worker, which must wait for the old one to release control. The lifecycle is the browser protecting open pages from a version swap mid-session.

How it works

Registration fetches the script; install runs precaching; the worker passes to waiting if an existing worker controls open clients; activate fires when that count reaches zero, and old caches are typically purged here. The browser checks for script updates on navigation and push, honoring cache headers on the worker script itself.

When to manage it

Any deployable app with precaching needs an update policy: prompt the user when a waiting worker exists and reload on consent, or version caches and prune in activate. Debug with update cycles in devtools rather than unregister, which hides real-world behavior.

Pitfalls

skipWaiting plus clients.claim mid-session can serve a new worker against pages whose lazy chunks were precached by the old one. The worker script should be served with no long cache lifetime, or update checks keep finding the stale bytes. Registration path determines scope; a worker at a deep path silently fails to control the site root.