Glossary / Service Workers

Service Workers

A Service Worker is an event-driven worker that can intercept network requests for its controlled clients and enable offline caching, request routing, and background capabilities. It runs separately from a page and has no direct DOM access. The browser may stop and restart it between events, so it must be designed as a short-lived event handler rather than a permanently running process.

Lifecycle and caching

A service worker is registered by a secure context (HTTPS, with localhost exceptions), downloads/installs, may wait before activation while older controlled pages remain, then controls clients according to scope and lifecycle rules. install, activate, fetch, and other events use event.waitUntil() to keep the worker alive for asynchronous work. Update handling and cache versioning must avoid mixing incompatible assets.

For fetch interception, define cache strategies per resource: cache-first, network-first, stale-while-revalidate, or network-only. Never cache sensitive or personalized responses without an explicit policy. Handle quota eviction and offline failures. A service worker is not a general replacement for a server, nor a guarantee that the browser retains cached data forever.

Test first install, update waiting, multiple tabs on different versions, offline transitions, and recovery after termination. Avoid relying on hidden in-memory state; persist durable state in IndexedDB or Cache Storage when appropriate.

Interview questions

  1. Can a service worker access the DOM? No.
  2. Why must it be stateless between events? The browser can terminate it and recreate it at any time.
  3. What does waitUntil do? Extends the event lifetime until an associated Promise settles.
  4. What security requirement applies? Secure context (HTTPS, with localhost development exceptions).
  5. What caching risks matter? Stale/version-mixed assets, sensitive data, quota, and incorrect strategy.

References