Service Worker Lifecycle
A Service Worker is an event-driven network proxy sitting between your tabs and the network. Its install -> waiting -> activate state machine prevents a newly deployed worker from hijacking an already-open tab mid-session and serving mismatched JS chunks.
Service Worker: Install, Waiting & Activation
Step through how a new sw.js version installs in parallel, waits for open tabs, and claims control.
Browser detects a byte-different sw.js. install event runs and waits for event.waitUntil(caches.open...).
self.addEventListener('install', (e) => e.waitUntil(precache()));- workerV1
- activated (controlling Tab 1)
- workerV2
- installing
- tab1ServedBy
- v1
Under the Hood
A Service Worker runs on its own Event Loop thread with zero DOM access, acting like a local reverse proxy inside the browser. Because two tabs of the same origin share one worker, the spec enforces strict version handoff rules:
- On navigation, the browser checks
sw.jsfor a single byte difference (governed by HTTP Caching Directives). - If changed,
v2runsinstallin the background whilev1keeps serving existing tabs. v2enters thewaitingstate until everyv1-controlled tab closes, unlessself.skipWaiting()forces immediate takeover.- Once
activateruns,v2purges staleCacheStoragebuckets and interceptsfetchevents.
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys.filter((k) => k !== CACHE_VERSION).map((k) => caches.delete(k))
)
)
);
});Problem Genealogy
- 2009 (HTML5 AppCache): Declarative manifest file with infamous "always serves stale HTML first" traps; quietly deprecated.
- 2014 (W3C Service Workers): Replaced AppCache with imperative JS
fetchinterception and explicitwaitingsemantics. - 2020+ (Navigation Preload): Fixed the worker startup penalty by letting the browser fetch navigation HTML in parallel while the worker thread boots.
Production Pitfalls
- Blindly calling
skipWaiting(): Forcingv2to take over an openv1tab causes lazy-loadedv1dynamic imports to fail withChunkLoadErroror servev2modules tov1HTML. - Long
max-ageonsw.js: Cachingsw.jswithmax-age=31536000locks users onto an old worker for a year; always servesw.jswithCache-Control: no-cache.
- When not to use a Service Worker: On content sites that only need fast static asset caching, HTTP
immutableheaders and CDN edge caching deliver zero startup latency without worker thread wakeups.
Connections & Logical Next Steps
Coordinating Service Worker activation with open tab storage versions prevents old JS bundles from reading new schemas.
Offline-capable local-first apps pair IndexedDB persistence with a Service Worker shell.
Service Worker fetch interception handles real browser Request/Response objects in-process.
sw.js itself must be served with no-cache so browser update checks detect new worker bytes.
Service workers execute in an isolated worker event loop and wake only for functional events.