本文详细介绍浏览器中的 CacheStorage API,它是 ServiceWorker 规范的一部分,用于存储 HTTP 响应对象。通过 caches.open、put、match 和 delete 等方法,开发者可以高效管理缓存集合。文章结合代码示例,解析了 CacheStorage 与 Cache 对象的关系、异步操作特性以及与 localStorage 的区别,帮助理解现代 Web 缓存机制。
CacheStorage 概述与基本概念
提到 localStorage,大家可能都不陌生,但本地存储的范畴远不止于此。此前我们讨论过 sessionStorage,如今还有一个更为强大的 CacheStorage。它专门用于存储 Response 对象,即对 HTTP 响应进行缓存。虽然 localStorage 也能实现类似功能,但 CacheStorage 在此场景下显得更为专业。 在浏览器环境中,CacheStorage 的全局引用名为 caches(而非驼峰命名的 cacheStorage),该接口定义于 ServiceWorker 规范之中。CacheStorage 本质上是多个 Cache 对象的集合,而每个 Cache 对象又可以存储多个 Response 对象。 不再多言,直接看示例代码。
<script>
caches.delete('c1');
caches.delete('c2');
Promise.all([
caches.open('c1').then(function(cache) {
return cache.put('/hehe', new Response('aaa', { status: 200 }));
}),
caches.open('c2').then(function(cache) {
return cache.put('/hehe', new Response('bbb', { status: 200 }));
})
]).then(function() {
return caches.match('/hehe');
}).then(function(response) {
return response.text();
}).then(function(body) {
console.log(body);
});
</script>
CacheStorage API 核心操作与注意事项
首先,调用 caches 上的 open 方法,可以异步获取一个 Cache 对象的引用。在该对象上,可以使用 put 方法存入数据(参数为 URL 和 Response 对象),或通过 match 方法取出数据(传入 URL 以获取对应的 Response 对象)。 match 方法既可以在 Cache 对象上调用,也可以在 CacheStorage 对象上调用。例如,在上述示例中打开了两个 Cache,并都写入了一个名为 /hehe 的 URL。在写入操作完成后,若在外部的 CacheStorage 上调用 match 方法匹配 /hehe,返回结果是不确定的(目前未找到明确定义此行为的规则)。 尽管上述示例中仅向 Cache 对象 put 了一个数据项,但 Cache 对象本身支持存储更多的 URL/Response 对,并提供了 delete(用于删除)、keys(用于遍历)等方法。需要注意的是,Cache 不像 localStorage 那样提供 clear 方法。如果必须清空一个 Cache,可以直接在 CacheStorage 上将该 Cache 整体 delete 掉,然后重新 open 一个新的 Cache。 这套 API 与 ServiceWorker 同属一家,通常应用于 ServiceWorker 场景中。其整体设计风格与 ServiceWorker 一致,均基于 Promise 异步模型构建。