--- title: CacheStorage.open() slug: Web/API/CacheStorage/open translation_of: Web/API/CacheStorage/open ---
{{APIRef("Service Workers API")}}{{SeeCompatTable}}
{{domxref("CacheStorage")}} 接口的 open()
方法返回一个resolve为匹配 cacheName
的 {{domxref("Cache")}} 对象的 {{jsxref("Promise")}} .
注意: 如果指定的 {{domxref("Cache")}} 不存在,则使用该 cacheName
创建一个新的cache,并返回一个resolve为该新 {{domxref("Cache")}} 对象的{{jsxref("Promise")}}.
// "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 });
一个resolve为请求的 {{domxref("Cache")}} 对象的 {{jsxref("Promise")}} .
此示例来自于MDN sw-test example (请参阅 sw-test running live)。这里,等待 {{domxref("FetchEvent")}} 事件触发。我们构建自定义响应,像这样:
v1
cache,使用 {{domxref("Cache.put","Cache.put()")}} 将默认网络请求放入 cache 中,并使用 return response.clone()
返回默认网络请求的克隆副本。最后一个是必须的,因为 put()
使用响应主体。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 |
---|---|---|
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}} | {{Spec2('Service Workers')}} | Initial definition. |
{{Compat("api.CacheStorage.open")}}