乐闻世界logo
搜索文章和话题

What are the common caching strategies in PWA? What scenarios are they suitable for?

2月18日 21:52

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:

javascript
self.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:

javascript
self.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:

javascript
self.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:

javascript
self.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:

javascript
self.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:

javascript
self.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 TypeRecommended StrategyReason
Static resources (CSS, JS, images)Cache FirstRarely changes, prioritize speed
API requestsNetwork FirstNeed fresh data
HTML documentsNetwork First with Cache FallbackNeed fresh but can fallback
Font filesCache FirstRarely changes, available offline
Real-time dataNetwork OnlyMust be fresh
Offline pagesCache OnlyPre-cached, completely offline

Cache Management

Cache Version Control

javascript
const 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

  1. Mix Strategies: Use different strategies for different resource types
  2. Set Cache Expiration: Set reasonable expiration times for caches
  3. Monitor Cache Size: Avoid using too much storage space
  4. Provide Offline Pages: Provide friendly prompts when network is unavailable
  5. Test Cache Behavior: Test caching strategies under different network conditions
  6. Update Mechanism: Implement automatic update mechanisms to ensure content freshness
标签:PWA