Under The Hood
frontend browser W3C Service Worker API / PWA Standards

Service Workers: Lifecycle (Install, Activate), Cache Storage, and Fetch Interception

Last updated
Prerequisites:
Web Workers architecture
HTTP Caching and Fetch API
  • browser
  • service-worker
  • pwa
  • offline
  • cache-storage
  • fetch

Read at your depth

The practical view

A Service Worker is an event-driven background worker running on its own origin-scoped thread. Its lifecycle has three main phases: Registration, Installation (`install` event where you pre-cache static assets), and Activation (`activate` event where you purge outdated caches). Once active, it intercepts all network calls from controlled pages via the `fetch` event using `event.respondWith(caches.match(event.request))`.

The same idea in other frameworks

react equivalent
Workbox / PWA plugin registering precache manifests inside `serviceWorker.register()`.

Legacy vs modern

Network-Only Fetch vs Offline Cache-First Interception

Standard web pages fail with a dinosaur error offline; a Service Worker intercepts requests and serves cached assets instantly.

before → after
Direct Uncached Network Request
fetch('/api/data'); // ❌ Crashes immediately when user is offline
Service Worker Cache-First Interception
event.respondWith(caches.match(event.request)); // ✅ NEW: Instant offline capability

Interview gotchas

Context

Interviewers test your knowledge of the Service Worker update cycle and multi-tab versioning safety.

The mechanical answer

To prevent breaking running applications when different tabs share state, the browser installs the new Service Worker in the background and places it into the **waiting** state. The new worker will not take control until *all* tabs controlled by the old worker are completely closed. To force immediate takeover, call `self.skipWaiting()` in the `install` handler and `self.clients.claim()` in the `activate` handler.

Trap

Refreshing a single tab does not necessarily activate the waiting worker if other tabs with the same origin remain open.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.