Cache-First Strategy
What you'll learn: How to serve cached resources instantly before attempting network requests, delivering blazing-fast load times for repeat visits.
The cache-first strategy (also called "cache-falling-back-to-network") prioritizes speed by checking your service worker's cache storage before making any network request. If the resource exists in cache, it's returned immediately. Only if it's not cached does the service worker fetch it from the network.
Think of it like checking your refrigerator before going to the grocery store. Why drive across town if you already have what you need at home?
How It Works
When a fetch event is intercepted, your service worker:
- Checks the cache for a matching request
- Returns the cached response if found (instant!)
- Falls back to a network request if not found
- Optionally caches the network response for next time
Implementation Pattern
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((cachedResponse) => {
// Return cached version if available
if (cachedResponse) {
return cachedResponse;
}
// Otherwise, fetch from network
return fetch(event.request);
})
);
});
This strategy is ideal for static assets that rarely change: logos, stylesheets, JavaScript bundles, fonts, and images. Users get near-instant page loads on repeat visits because resources load from local cache rather than waiting for network round-trips.
When to Use It
Cache-first works best for resources where speed matters more than freshness. It's perfect for versioned assets (app.v123.js) but problematic for frequently-updated content like API responses or real-time data.
Key Takeaway: Cache-first strategy delivers maximum speed by serving cached resources immediately and only hitting the network as a fallback—perfect for static assets that don't change often.