Network & PerformanceBaseline · Widely

Service Worker Lifecycle

Mental Model

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.

Interactive Simulator

Service Worker: Install, Waiting & Activation

Step through how a new sw.js version installs in parallel, waits for open tabs, and claims control.

Step 1 / 3: 1. Installing (Precache)

Browser detects a byte-different sw.js. install event runs and waits for event.waitUntil(caches.open...).

self.addEventListener('install', (e) => e.waitUntil(precache()));
Internal State / Memory
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:

  1. On navigation, the browser checks sw.js for a single byte difference (governed by HTTP Caching Directives).
  2. If changed, v2 runs install in the background while v1 keeps serving existing tabs.
  3. v2 enters the waiting state until every v1-controlled tab closes, unless self.skipWaiting() forces immediate takeover.
  4. Once activate runs, v2 purges stale CacheStorage buckets and intercepts fetch events.
JS
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 fetch interception and explicit waiting semantics.
  • 2020+ (Navigation Preload): Fixed the worker startup penalty by letting the browser fetch navigation HTML in parallel while the worker thread boots.

Production Pitfalls

Production Pitfall
  • Blindly calling skipWaiting(): Forcing v2 to take over an open v1 tab causes lazy-loaded v1 dynamic imports to fail with ChunkLoadError or serve v2 modules to v1 HTML.
  • Long max-age on sw.js: Caching sw.js with max-age=31536000 locks users onto an old worker for a year; always serve sw.js with Cache-Control: no-cache.
When Not to Use
  • When not to use a Service Worker: On content sites that only need fast static asset caching, HTTP immutable headers and CDN edge caching deliver zero startup latency without worker thread wakeups.

Connections & Logical Next Steps

Seen in Architecture Autopsies