Retrieving Cached Responses
You'll learn how to retrieve stored resources from the Cache API using cache.match() and caches.match().
Now that you've learned to add resources to cache storage, the real power comes from retrieving them when needed—especially when the network is slow or unavailable.
Understanding the Retrieval Methods
Think of the Cache API like a library system. You've already learned how to add books (resources) to specific shelves (named caches). Now you need to know how to find and check out those books when someone requests them.
There are two main methods for retrieving cached responses:
cache.match()
This method searches within a specific cache you've already opened. You provide a request (usually a URL string), and it returns a Promise that resolves to the matching cached response, or undefined if nothing is found.
// Open a specific cache first
caches.open('my-cache-v1').then(cache => {
// Search within this cache only
cache.match('/styles.css').then(response => {
if (response) {
console.log('Found in cache!');
// Use the cached response
} else {
console.log('Not found in this cache');
}
});
});
caches.match()
This global method searches across all caches automatically, checking each one until it finds a match. It's more convenient when you don't care which cache holds the resource.
// Search all caches at once
caches.match('/app.js').then(response => {
if (response) {
console.log('Found somewhere in cache storage!');
return response;
} else {
console.log('Not cached anywhere, fetch from network');
}
});
Key Takeaway: Use cache.match() to search a specific cache you've opened, or caches.match() to search all caches at once—both return Promises that resolve to cached Response objects or undefined when no match exists.