A programmable cache
A service worker is a background script that intercepts network requests and decides how to respond. It enables offline support and fine grained caching using the cache storage API.
The common strategies
Each request type suits a different balance of speed and freshness.
- Cache first: serve from cache, fall back to network. Best for hashed static assets.
- Network first: try the network, fall back to cache on failure. Best for fresh data like an API.
- Stale while revalidate: serve the cached copy immediately, then update the cache in the background for next time.
- Network only and cache only: the simple extremes.
Lifecycle care
A worker installs, activates, then controls pages. You must version the cache name and clean old caches on activate, or users get stuck on stale assets.
- Precache the app shell during install.
- Use stale while revalidate for assets that can lag one visit.
- Never cache responses with errors or partial content.
The strategy is chosen in the fetch event handler based on the request URL or destination.
Key idea
Pick a strategy per resource: cache first for static assets, network first for fresh data, and stale while revalidate for the speed and freshness blend.