Performance

Service worker

Service worker is a JavaScript file the browser runs in the background, between the page and the network. It can intercept requests, serve cached responses, and keep a site working when the connection drops.

How it is measured

Open DevTools, Application, Service Workers, to see its status (installing, waiting, activated) and script URL. In the Network panel, responses it handles show '(ServiceWorker)' as their size. Cache Storage lists what it stored.

Measure its effect by comparing repeat-visit timings with and without it. TTFB for navigations often drops from hundreds of milliseconds to under 50 ms when the worker answers from cache. Also measure its own startup, which adds a few tens of milliseconds when the worker has been idle.

Worked example

A weather site registers a worker that precaches `/offline.html` and 11 static assets (210 KB) and answers navigations network-first with a 3 s timeout, then falls back to cache. On a train between towns a visitor loses signal, and the worker returns the last cached forecast in 90 ms instead of a browser error page.

Later a bug ships: the worker caches `index.html` cache-first with no expiry. For nine days returning users see the old homepage because the old worker keeps serving it. The fix is a new worker version with `skipWaiting`, a versioned cache name, and cleanup of the old cache.

How it differs

A service worker is the mechanism. A PWA is a site that uses one together with a manifest to be installable. A service worker also works on ordinary sites purely for caching or push. It runs separately from the page and cannot touch the DOM directly.

Common errors

Cache-first on HTML. No versioned cache names. Forgetting that HTTPS is required outside localhost. Testing only the first visit. Ignoring the 'waiting' state, so updates never activate. Registering the worker so early that it delays LCP.

In practice

Start with a small worker that precaches an offline page and applies stale-while-revalidate to static assets. Register it after the load event. Test the update path by deploying twice and confirming a returning visitor gets the new version within two page loads. Keep an unregister route ready.

See also

Progressive web app, Stale-while-revalidate

Sources

Count this on a real site.

Watch my website