Field Notes
All posts

Service workers and the offline-first web

A service worker sits between your page and the network. That position is powerful, and it deserves care.

A programmable proxy

A service worker is a script the browser runs separately from your page, positioned between the page and the network. Every request the page makes passes through it, and the worker can answer from a cache, go to the network, or combine the two. That makes it the foundation for offline support, instant repeat visits, and background synchronization.

Caching strategies

Cache first

Check the cache and use the response if present; otherwise go to the network. Ideal for fingerprinted static assets that never change at a given URL.

Network first

Try the network and fall back to the cache when offline or slow. Suits HTML and API responses where freshness matters but an older copy is better than nothing.

Stale while revalidate

Serve from cache immediately, then fetch a fresh copy in the background for next time. A good balance for content that changes occasionally, such as an article list.

Network only

Some requests, like payments or authentication, must never be served from a cache. Make that explicit.

The update problem

Service workers are sticky. Once installed, a worker keeps controlling the page until a new version is installed and activated, and by default activation waits until every tab using the old worker has closed. A bug in a service worker can therefore outlive the deploy that fixes it.

Practical safeguards:

  1. Keep the worker script small and serve it with no caching, so the browser always checks for updates.
  2. Version cache names, and delete old caches during activation.
  3. Have a kill switch: a deployable worker that unregisters itself and clears caches.
  4. Tell users when an update is ready, and offer a reload.

Offline pages

The simplest valuable use is an offline fallback. Precache a small page that explains the visitor is offline, and serve it when a navigation request fails. This replaces the browser's generic error with something on-brand and, ideally, useful, such as recently viewed articles.

Do not cache everything

It is tempting to precache the whole site. On a large site this downloads megabytes the visitor will never use and consumes their storage. Precache only the application shell and critical assets; cache other resources as they are actually requested.

Debugging

Browser developer tools have a dedicated panel for service workers, showing registration, status, and caches. During development, enable the option to update the worker on every reload, or you will spend an afternoon wondering why your changes do not appear.

When to skip it

A content site that loads quickly and has no meaningful offline use case may not need a service worker at all. The complexity is real, and a simple site with good HTTP caching is often fast enough.