Responding with Cached Resources
What you'll learn: How to serve cached files from a service worker to enable offline functionality.
In the previous lesson, you learned how the fetch event intercepts network requests. Now it's time to put that power to work: instead of letting the request go to the network, you can respond with a cached copy of the resource.
The Core Idea
Think of your service worker as a helpful librarian. When someone asks for a book (a network request), the librarian checks the shelf (the cache) first. If the book is there, they hand it over immediately—no need to order it from a distant warehouse (the network). This makes your app work even when the user is offline.
How It Works
Inside your fetch event listener, you use event.respondWith() to provide a custom response. Instead of letting the browser fetch from the network, you query the cache:
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((cachedResponse) => {
// If we have a cached version, return it
if (cachedResponse) {
return cachedResponse;
}
// Otherwise, fetch from network
return fetch(event.request);
})
);
});
The caches.match() method searches all your caches for a resource matching the request. If found, you return the cached response. If not, you fall back to the network using fetch().
Why This Matters
This pattern is the foundation of offline-first web apps. Users can continue browsing previously visited pages, viewing images, or using your app's core functionality—even without an internet connection.
Key Takeaway: Use event.respondWith(caches.match(event.request)) in your service worker's fetch handler to serve cached resources first, enabling offline functionality and instant loading for repeat visits.