2.11 Service workers

Real offline support, and a real way to break your site.

Service Workers for caching / performing heavy tasks

A service worker sits between the page and the network, intercepting requests. It enables genuine offline support, instant repeat loads, and background sync.

It is also the most dangerous item in this handbook. A service worker persists after deployment. Ship a broken one and returning users get the broken version from their own device — not your server — until it updates or they clear site data.

Do not add one for performance alone. HTTP caching gets you most of the benefit with none of the risk. Add a service worker when you need offline capability, and treat it as a feature with its own testing.

Caching strategies

Match the strategy to the resource:

StrategyUse for
Cache firstFingerprinted assets that never change
Network firstHTML and API data where freshness matters
Stale while revalidateContent that can lag slightly
Network onlyAnything non-idempotent — never cache a POST
// Cache-first, for immutable assets only.
self.addEventListener("fetch", (event) => {
  if (!event.request.url.includes("/assets/")) return;
  event.respondWith(
    caches.match(event.request).then((hit) => hit ?? fetch(event.request)),
  );
});

Use a library

Hand-written service workers get the update lifecycle wrong in subtle ways. Workbox handles precaching, routing, expiry and updates, and is what most framework PWA plugins use underneath.

Plan the escape hatch

Before shipping one, know how you would disable it. A service worker that unregisters itself and clears its caches, ready to deploy, is worth writing in advance — while the site still works.

Requires HTTPS.

On this page