CacheStorage.open()
CacheStorage
接口的 open()
方法返回一个 resolve 为匹配 cacheName
的 Cache
对象的 Promise
.
语法
js
// "caches" is a global read-only variable, which is an instance of CacheStorage,
// For more info, refer to: https://developer.mozilla.org/zh-CN/docs/Web/API/caches
caches.open(cacheName).then(function (cache) {
// Do something with your cache
});
参数
- cacheName
-
要打开的 cache 对象 name.
返回值
示例
此示例来自于 MDN sw-test example (请参阅 sw-test running live)。这里,等待 FetchEvent
事件触发。我们构建自定义响应,像这样:
- 使用
CacheStorage.match()
检查CacheStorage
中是否存在匹配请求,如果存在,则使用它。 - 如果没有,使用
CacheStorage.open()
打开v1
cache,使用Cache.put()
将默认网络请求放入 cache 中,并使用return response.clone()
返回默认网络请求的克隆副本。最后一个是必须的,因为put()
使用响应主体。 - 如果此操作失败(例如,因为网络已关闭),则返回备用响应。
js
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 |
---|
Service Workers # cache-storage-open |
浏览器兼容性
BCD tables only load in the browser