Managing Multiple Caches
You'll learn how to list all named cache instances and remove specific caches using caches.keys() and caches.delete().
The Core Idea
As your application evolves, you might create multiple caches for different purposes—one for images, one for API responses, one for CSS files, etc. You need a way to see what caches exist and clean up old or unused caches to prevent storage bloat.
Think of it like managing folders on your computer. You need to occasionally list all your folders to see what you have, and delete old project folders you no longer need.
Listing All Caches
The caches.keys() method returns a promise that resolves to an array of all cache names:
caches.keys().then(cacheNames => {
console.log('All caches:', cacheNames);
// Output might be: ['my-cache-v1', 'my-cache-v2', 'images-cache']
});
Deleting a Specific Cache
To remove an entire cache by name, use caches.delete():
caches.delete('my-cache-v1').then(success => {
if (success) {
console.log('Cache deleted successfully');
} else {
console.log('Cache not found');
}
});
Practical Example: Cleaning Up Old Versions
A common pattern is deleting outdated cache versions when updating your app:
const currentCache = 'my-cache-v3';
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== currentCache) {
return caches.delete(cacheName);
}
})
);
}).then(() => {
console.log('Old caches cleaned up');
});
This code keeps only the current cache version and removes all others.
Key Takeaway: Use caches.keys() to list all cache names and caches.delete() to remove specific caches by name—essential for managing cache versions and preventing storage overflow.