This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
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.
// "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 });
A Promise
that resolves to the requested Cache
object.
This example 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:
CacheStorage
using CacheStorage.match()
. If so, serve that.v1
cache using CacheStorage.open()
, put the default network request in the cache using Cache.put()
and return a clone of the default network request using return response.clone()
. The last is necessary because put()
consumes the response body.var cachedResponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(response) { caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); });
Specification | Status | Comment |
---|---|---|
Service Workers The definition of 'CacheStorage: open' in that specification. | Working Draft | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 40 | Yes | 44
|
No | 27 | 11.1 |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | 40 | 40 | Yes | 44 | 27 | Yes | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/open