The power of service workers comes from choosing the right caching strategy for each type of resource. Different content needs different strategies — static assets, API responses, and images each have their own optimal approach.
Strategy Overview
| Strategy | Network | Cache | Best For |
|---|---|---|---|
| Cache First | Backup | Primary | Static assets, fonts, icons |
| Network First | Primary | Backup | API data, dynamic HTML |
| Stale While Revalidate | Both | Both | Frequently updated content |
| Cache Only | No | Only | Offline-critical assets |
| Network Only | Only | No | Analytics, real-time data |
Cache First (Cache Falling Back to Network)
Check the cache first. If the resource is cached, return it immediately. Otherwise, fetch from the network and cache the response for next time.
Use for: CSS, JavaScript, fonts, images — files that rarely change. When you deploy a new version, update the cache name to force a refresh.
Network First (Network Falling Back to Cache)
Try the network first. If it fails (user is offline), fall back to the cached version.
Use for: API endpoints, HTML pages — content where freshness matters most, but you still want offline access to the last known version.
Network First with Timeout
Avoid waiting too long for a slow network by adding a timeout:
Stale While Revalidate
Return the cached version immediately (fast), then fetch a fresh version in the background for next time.
Use for: User avatars, social feeds, blog posts — content that should load fast but also stay reasonably up-to-date.
Cache Only
Only serve from cache. Never hit the network. Use for resources cached during installation.
Network Only
Always go to the network. Never cache. Use for real-time data or analytics.
async function networkOnly(request) {
return fetch(request);
}Implementing a Strategy Router
Apply different strategies based on the request type:
Cache Size Management
Caches can grow large. Limit the number of entries:
Cache Expiration
Add time-based expiration to cached responses:
Precaching vs Runtime Caching
| Type | When | What |
|---|---|---|
| Precache | During install event | App shell, critical assets |
| Runtime | During fetch event | API responses, images, pages |
Practical Exercise
Build a complete caching layer with multiple strategies:
Key Takeaways
- Cache First is fastest for static assets that rarely change.
- Network First ensures fresh data with offline fallback for APIs and dynamic content.
- Stale While Revalidate balances speed and freshness by serving cached data while updating in the background.
- Route different strategies based on request type (assets, API, pages).
- Manage cache size with entry limits and time-based expiration to prevent unbounded growth.