Skip to content

Offline strategies

Outcome: an app that loads and stays usable with no network, because the service worker serves the right thing for each kind of request. There is no single “offline mode” — offline is a set of per-request decisions about when to trust the cache and when to trust the network.

This builds on a registered service worker; if you don’t have one yet, do Getting started first. The worker’s registration and update model is described in the service worker lifecycle reference.

Different requests want different trade-offs between freshness and resilience:

Request type Strategy Why
App shell (HTML, CSS, JS) Cache-first / precache Instant load; update on the next visit.
API / dynamic data Network-first, fall back to cache Fresh when online, still usable offline.
Images, fonts Stale-while-revalidate Fast paint, refresh in the background.
Rarely-changing assets Cache-first with versioning Avoid refetching immutable files.
  1. Precache the app shell on install. In the worker’s install event, open a versioned cache and add the core HTML/CSS/JS that every view needs. This is what makes the first paint work offline.

  2. Serve matched requests from cache in fetch. Intercept fetch, apply the strategy from the table above based on the request, and fall back gracefully when both cache and network miss. The interception model is in the service worker reference.

  3. Version and clean up caches on activate. Name caches with a version, and in activate delete old versions so stale assets don’t accumulate. The lifecycle reference explains when activate runs.

  4. Provide an offline fallback page. For navigations that miss the cache while offline, return a friendly cached fallback instead of the browser error.

  5. Defer writes with Background Sync where supported. Queue failed POSTs and replay them when connectivity returns — but treat it as progressive enhancement. Confirm support first in the background-sync compatibility data, since it is not available everywhere.

  6. Mind the storage budget. Caches count against the origin’s quota, and eviction can reclaim them. For data that must survive, see storage persistence.

Toggle offline in your browser’s dev tools (not just airplane mode) and reload. A real offline test reloads the installed app cold, not a warm tab with everything already in memory.

← Back to the Guides overview.