--- title: CacheStorage slug: Web/API/CacheStorage tags: - API - CacheStorage - ServiceWorker translation_of: Web/API/CacheStorage ---
{{APIRef("Service Workers API")}}{{SeeCompatTable}}
CacheStorage 接口表示 {{domxref("Cache")}} 对象的存储。它提供了一个 {{domxref("ServiceWorker")}} 、其它类型worker或者 {{domxref("window")}} 范围内可以访问到的所有命名cache的主目录(它并不是一定要和service workers一起使用,即使它是在service workers规范中定义的),并维护一份字符串名称到相应 {{domxref("Cache")}} 对象的映射。
CacheStorage 同样暴露了 {{domxref("CacheStorage.open()")}} 和 {{domxref("CacheStorage.match()")}}方法。使用 {{domxref("CacheStorage.open()")}} 获取 {{domxref("Cache")}} 实例。使用 {{domxref("CacheStorage.match()")}} 检查给定的 {{domxref("Request")}} 是否是 CacheStorage 对象跟踪的任何 {{domxref("Cache")}} 对象中的键。
你可以通过 {{domxref("WorkerGlobalScope.caches", "caches")}} 属性访问 CacheStorage .
SecurityError reject. 测试时,你可以在Firefox Devtools选项/齿轮菜单中通过选中"通过HTTP启用 Service Workers (当工具箱打开时)" 选项来绕开这个限制。cacheName 匹配的 {{domxref("Cache")}} 对象,则返回一个resolve为true的 {{jsxref("Promise")}} .cacheName (如果不存在则创建一个新的cache)的 {{domxref("Cache")}} 对象cacheName 的 {{domxref("Cache")}} 对象,如果找到,则删除 {{domxref("Cache")}} 对象并返回一个resolve为true的 {{jsxref("Promise")}} 。如果没有找到 {{domxref("Cache")}} 对象,则返回 false.此代码片段来自于MDN sw-test example (请参阅sw-test running live.)此 service worker 脚本等待 {{domxref("InstallEvent")}} 触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理应用程序的安装过程。这包括调用 {{domxref("CacheStorage.open")}} 创建一个新的cache,然后使用 {{domxref("Cache.addAll")}} 向其添加一系列资源。
在第二个代码块,我们等待 {{domxref("FetchEvent")}} 触发。我们构建自定义相应,像这样:
cache.put(event.request, response.clone()).) 将请求的clone副本添加到它。最后,使用 {{domxref("FetchEvent.respondWith")}} 返回自定义响应最终等于的内容。
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
'/sw-test/style.css',
'/sw-test/app.js',
'/sw-test/image-list.js',
'/sw-test/star-wars-logo.jpg',
'/sw-test/gallery/bountyHunters.jpg',
'/sw-test/gallery/myLittleVader.jpg',
'/sw-test/gallery/snowTroopers.jpg'
]);
})
);
});
this.addEventListener('fetch', function(event) {
var response;
event.respondWith(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');
}));
});
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}} | {{Spec2('Service Workers')}} | Initial definition. |
{{Compat("api.CacheStorage")}}