This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.
The open()
method of the CacheStorage
interface returns a Promise
that resolves to the Cache
object matching the cacheName
.
Note: If the specified Cache
does not exist, a new cache is created with that cacheName and a
Promise
that resolves to this new Cache
object is returned.
Syntax
// "caches" is a global read-only variable, which is an instance of CacheStorage, // For more info, refer to: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/caches caches.open(cacheName).then(function(cache) { //do something with your cache });
Returns
a Promise
that resolves to the requested Cache
object.
Parameters
- cacheName
- The name of the cache you want to open.
Examples
This code snippet is from the MDN sw-test example (see sw-test running live). Here we wait for a FetchEvent
to fire. Then we construct a custom response like so:
- Check whether a match for the request is found in the
CacheStorage
usingCacheStorage.match
. If so, serve that. - If not, open the
v1
cache usingCacheStorage.open
, put the default network request in the cache usingCache.put
and return a clone of the default network request usingreturn response.clone()
— necessary becauseput()
consumes the response body. - If this fails (e.g., because the network is down), return a fallback response.
var response; var cachedResponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); });
Specifications
Specification | Status | Comment |
---|---|---|
Service Workers The definition of 'CacheStorage' in that specification. |
Working Draft | Initial definition. |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 40.0 | 44 (44)[1] | No support | ? | No support |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | No support | No support | 44.0 (44) | (Yes) | (Yes) | (Yes) | 40.0 |
[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)