Lesson 9 / 29
Network-first pattern
Implement network-first strategy: fetch fresh content, fall back to cache if offline.
When to use network-first
Network-first prioritizes fresh content from the server. If the network fails, fall back to cache. Best for HTML pages and frequently updated content.
Network-first implementation
Fetch from network first, cache the response, and fall back to cache on network error.
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request)
.then(response => {
const clone = response.clone();
caches.open('v1').then(cache => cache.put(event.request, clone));
return response;
})
.catch(() => caches.match(event.request))
);
});
Output:
Always attempts fresh content; serves cached version if network unavailable.
Quick check
Quick check: When should you use network-first caching?
- For HTML pages and frequently updated content
- For static assets like images and fonts
- Only for old browsers
Answer
For HTML pages and frequently updated content — Network-first is ideal for content that changes often and requires freshness.