The caches object is available globally in secure contexts—both in window and worker scopes. It serves as the entry point for managing named cache instances. To retrieve or create a cache by name: ```
caches.open('assets-v2').then(cacheInstance => {
console.log('Cache instance:', cacheInstance);
});
Key static methods on `caches` include: - `caches.has('assets-v2')` — resolves to `true` if a cache with that name exists.
- `caches.delete('legacy-cache')` — removes the specified cache and returns a `Promise<boolean>`.
- `caches.match(request)` — searches acros *all* caches for a matching stored response.
- `caches.match(request, { cacheName: 'assets-v2' })` — restricts the search to a specific cache.
All of these return promises and are asynchronous. ### The `Cache` Instance
Each cache behaves like an isolated key-value store where keys are `Request` objects (or strings resolvable to them), and values are `Response` objects. #### `cache.add()` and `cache.addAll()`
These methods initiate network requests and store successful responses automatically. They’re ideal for pre-caching during service worker installation. Example: populating a cache with critical assets at install time: ```
self.addEventListener('install', event => {
const setupAssetsCache = async () => {
const assetCache = await caches.open('core-assets-2024');
await assetCache.addAll([
'/index.html',
'/js/main.bundle.js',
'/css/theme.css'
]);
};
event.waitUntil(setupAssetsCache());
});
Note: addAll() fails entirely if any requested URL returns a non-2xx status or fails to resolve. #### cache.put()
Unlike add, put() accepts explicit Request and Response objects—allowing you to inject synthetic responses, modify headers, or cache opaque or error responses. Example: injecting a fallback HTML page: ```
caches.open('offline-fallback').then(cache => {
const fallbackResponse = new Response(
'Offline mode active.',
{ headers: { 'Content-Type': 'text/html' } }
);
cache.put(new Request('/offline.html'), fallbackResponse);
});
#### `cache.match()`
Performs a lookup using request-matching semantisc (including method, URL, and Vary headers). Returns `undefined` if no match is found. ```
caches.open('api-responses').then(cache => {
cache.match('/api/user/123').then(response => {
if (response) {
response.json().then(data => console.log(data));
}
});
});
cache.delete()
Removes a cached entry by request key. Resolves to true on success, false otherwise. ```
caches.open('temp-data').then(cache => {
cache.delete('/api/logs/latest').then(deleted => {
console.log('Entry removed:', deleted);
});
});
</div></body></html>