Network-First Strategy
What you'll learn: How to configure your service worker to prioritize live network data while seamlessly falling back to cache when connections fail.
The Core Idea
The network-first strategy flips the cache-first approach on its head: it always attempts to fetch fresh content from the network first, only consulting the cache if the network request fails or times out. This ensures users see the most up-to-date data whenever they're online, while still functioning when connectivity drops.
Think of it like checking your mailbox before reading yesterday's newspaper. You want today's news if it's available, but you're happy to review yesterday's edition if the mail hasn't arrived yet.
When to Use Network-First
This strategy shines for content that changes frequently:
- News feeds or social media timelines
- API responses with real-time data
- User profile information
- Live sports scores or stock prices
You've already learned cache-first for static assets—network-first complements that for dynamic content.
Implementation Pattern
In your service worker's fetch event handler, you attempt the network request first, catch failures, and fall back to cache:
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request)
.then((networkResponse) => {
// Success! Clone and cache for future offline use
const responseClone = networkResponse.clone();
caches.open('dynamic-v1').then((cache) => {
cache.put(event.request, responseClone);
});
return networkResponse;
})
.catch(() => {
// Network failed—try cache
return caches.match(event.request);
})
);
});
The beauty here: successful network responses update your cache automatically, keeping offline content reasonably fresh.
Key Takeaway: Network-first strategy prioritizes fresh data from the network while maintaining offline resilience by falling back to cached content when connections fail—perfect for dynamic, frequently-updated resources.