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.
Pick a strategy per request type
Section titled “Pick a strategy per request type”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. |
-
Precache the app shell on install. In the worker’s
installevent, open a versioned cache and add the core HTML/CSS/JS that every view needs. This is what makes the first paint work offline. -
Serve matched requests from cache in
fetch. Interceptfetch, 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. -
Version and clean up caches on
activate. Name caches with a version, and inactivatedelete old versions so stale assets don’t accumulate. The lifecycle reference explains whenactivateruns. -
Provide an offline fallback page. For navigations that miss the cache while offline, return a friendly cached fallback instead of the browser error.
-
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.
-
Mind the storage budget. Caches count against the origin’s quota, and eviction can reclaim them. For data that must survive, see storage persistence.
Test it honestly
Section titled “Test it honestly”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.
Where to go next
Section titled “Where to go next”- Performance — caching strategy and perceived speed overlap heavily.
- Storage reference — quotas, persistence, and what eviction can take.
- Service worker reference — the API behind every step here.
← Back to the Guides overview.