PWA caching strategies determine how to handle network requests and cached resources. Different strategies are suitable for different scenarios.
Common Caching Strategies
1. Cache First
Use Case: Static resources (CSS, JS, images, fonts, etc.)
Implementation:
javascriptself.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { return response || fetch(event.request); }) ); });
Advantages:
- Fast response
- Reduced network traffic
- Available offline
Disadvantages:
- May return stale content
- Requires manual cache updates
2. Network First
Use Case: Dynamic content, API requests
Implementation:
javascriptself.addEventListener('fetch', event => { event.respondWith( fetch(event.request) .then(response => { const responseClone = response.clone(); caches.open('dynamic-cache').then(cache => { cache.put(event.request, responseClone); }); return response; }) .catch(() => { return caches.match(event.request); }) ); });
Advantages:
- Always returns fresh content
- Fallback when network fails
Disadvantages:
- Slower initial load
- Poor experience with unstable network
3. Stale While Revalidate
Use Case: Resources that need fast response but also maintain freshness
Implementation:
javascriptself.addEventListener('fetch', event => { event.respondWith( caches.match(event.request).then(cachedResponse => { const fetchPromise = fetch(event.request).then(networkResponse => { caches.open('dynamic-cache').then(cache => { cache.put(event.request, networkResponse.clone()); }); return networkResponse; }); return cachedResponse || fetchPromise; }) ); });
Advantages:
- Fast response (immediately return cache)
- Background cache update
- Balances speed and freshness
Disadvantages:
- Relatively complex implementation
- May briefly show stale content
4. Network Only
Use Case: Real-time data, sensitive operations like payments
Implementation:
javascriptself.addEventListener('fetch', event => { if (event.request.url.includes('/api/realtime')) { event.respondWith(fetch(event.request)); } });
Advantages:
- Ensures fresh data
- Suitable for high real-time requirements
Disadvantages:
- Cannot be used offline
- Depends on network stability
5. Cache Only
Use Case: Offline pages, preloaded resources
Implementation:
javascriptself.addEventListener('fetch', event => { if (event.request.url.includes('/offline')) { event.respondWith(caches.match(event.request)); } });
Advantages:
- Completely available offline
- Fastest response
Disadvantages:
- Requires pre-caching
- Content may be stale
6. Cache First with Network Fallback
Use Case: Need fast response but try network when cache fails
Implementation:
javascriptself.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { if (response) { return response; } return fetch(event.request).catch(() => { return caches.match('/offline.html'); }); }) ); });
Choosing Caching Strategies
Choose appropriate strategy based on resource type:
| Resource Type | Recommended Strategy | Reason |
|---|---|---|
| Static resources (CSS, JS, images) | Cache First | Rarely changes, prioritize speed |
| API requests | Network First | Need fresh data |
| HTML documents | Network First with Cache Fallback | Need fresh but can fallback |
| Font files | Cache First | Rarely changes, available offline |
| Real-time data | Network Only | Must be fresh |
| Offline pages | Cache Only | Pre-cached, completely offline |
Cache Management
Cache Version Control
javascriptconst CACHE_VERSION = 'v1'; const CACHE_NAME = `my-app-${CACHE_VERSION}`; self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME).then(cache => { return cache.addAll([ '/', '/styles/main.css', '/scripts/main.js' ]); }) ); }); self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(cacheNames => { return Promise.all( cacheNames.map(cacheName => { if (cacheName !== CACHE_NAME) { return caches.delete(cacheName); } }) ); }) ); });
Cache Cleanup Strategy
- Regularly clean expired caches
- Clean specific resources on demand
- Limit cache size
Best Practices
- Mix Strategies: Use different strategies for different resource types
- Set Cache Expiration: Set reasonable expiration times for caches
- Monitor Cache Size: Avoid using too much storage space
- Provide Offline Pages: Provide friendly prompts when network is unavailable
- Test Cache Behavior: Test caching strategies under different network conditions
- Update Mechanism: Implement automatic update mechanisms to ensure content freshness