了解如何使用 Cache API 将您的应用数据设为可离线使用。
Cache API 是用于存储和检索网络请求及其相应响应的系统。这些可能是在运行应用的过程中创建的常规请求和响应,也可能仅用于存储数据供以后使用。
Cache API 旨在使服务工作器缓存网络请求,以便无论网络速度或可用性如何,它们都可以提供快速响应。不过,API 也可以用作常规存储机制。
在哪些地区推出了?
所有现代浏览器都支持 Cache API。它通过全局 caches
属性公开,因此您可以通过简单的特征检测来测试该 API 是否存在:
const cacheAvailable = 'caches' in self;
您可以通过窗口、iframe、Worker 或 Service Worker 访问 Cache API。
可以存储的内容
缓存仅存储一对 Request
和 Response
对象,分别表示 HTTP 请求和响应。不过,请求和响应可以包含可通过 HTTP 传输的任何一种数据。
可以存储多少数据?
简而言之,需要很多,至少数百 MB,可能数百 GB 或更多。虽然浏览器实现各不相同,但可用的存储空间量通常取决于设备上的可用存储空间量。
创建和打开缓存
如需打开缓存,请使用 caches.open(name)
方法,并将缓存名称作为单个参数传递。如果指定的缓存不存在,则系统会创建一个。此方法会返回使用 Cache
对象解析的 Promise
。
const cache = await caches.open('my-cache');
// do something with cache...
添加到缓存
您可以通过以下三种方式将项添加到缓存中:add
、addAll
和 put
。所有三种方法都会返回一个 Promise
。
cache.add
第一个是 cache.add()
。它需要一个参数:Request
或网址 (string
)。它会向网络发出请求并将响应存储在缓存中。如果提取失败,或者响应的状态代码不在 200 范围内,则系统不会存储任何内容,并且 Promise
会拒绝。请注意,非 CORS 模式的跨域请求无法存储,因为它们会返回 0
的 status
。此类请求只能通过 put
进行存储。
// Retreive data.json from the server and store the response.
cache.add(new Request('/data.json'));
// Retreive data.json from the server and store the response.
cache.add('/data.json');
cache.addAll
接下来是 cache.addAll()
。其工作原理与 add()
类似,但接受一组 Request
对象或网址 (string
)。这与为每个单独的请求调用 cache.add
类似,不同之处在于,如果未缓存任何单个请求,Promise
会拒绝。
const urls = ['/weather/today.json', '/weather/tomorrow.json'];
cache.addAll(urls);
在上述每种情况下,新条目都会覆盖任何匹配的现有条目。它使用的匹配规则与retrieving部分中介绍的匹配规则相同。
cache.put
最后是 cache.put()
,可用于存储来自网络的响应,或者创建并存储您自己的 Response
。它需要两个参数。第一个可以是 Request
对象,也可以是网址 (string
)。第二个必须是来自网络或由代码生成的 Response
。
// Retrieve data.json from the server and store the response.
cache.put('/data.json');
// Create a new entry for test.json and store the newly created response.
cache.put('/test.json', new Response('{"foo": "bar"}'));
// Retrieve data.json from the 3rd party site and store the response.
cache.put('https://example.com/data.json');
put()
方法比 add()
或 addAll()
更为宽松,可让您存储非 CORS 响应或其他响应的状态代码不在 200 范围内的响应。这将覆盖同一请求之前的所有响应。
创建 Request 对象
使用要存储的内容的网址创建 Request
对象:
const request = new Request('/my-data-store/item-id');
使用 Response 对象
Response
对象构造函数接受多种类型的数据,包括 Blob
、ArrayBuffer
、FormData
对象和字符串。
const imageBlob = new Blob([data], {type: 'image/jpeg'});
const imageResponse = new Response(imageBlob);
const stringResponse = new Response('Hello world');
您可以通过设置相应的标头来设置 Response
的 MIME 类型。
const options = {
headers: {
'Content-Type': 'application/json'
}
}
const jsonResponse = new Response('{}', options);
如果您已检索 Response
并希望访问其正文,可以使用多种辅助方法。每个都返回一个 Promise
,其解析为不同类型的值。
方法 | 说明 |
---|---|
arrayBuffer |
返回包含正文的 ArrayBuffer ,已序列化为字节。
|
blob |
返回 Blob 。如果 Response 是使用 Blob 创建的,则这个新 Blob 的类型也相同。否则,使用 Response 的 Content-Type 。
|
text |
将正文的字节解释为 UTF-8 编码字符串。 |
json |
将正文的字节解释为 UTF-8 编码的字符串,然后尝试将其解析为 JSON。返回生成的对象;如果字符串无法解析为 JSON,则抛出 TypeError 。
|
formData |
将正文的字节解释为 HTML 形式,编码为 multipart/form-data 或 application/x-www-form-urlencoded 。返回 FormData 对象;如果数据无法解析,则抛出 TypeError 。
|
body |
返回正文数据的 ReadableStream。 |
例如:
const response = new Response('Hello world');
const buffer = await response.arrayBuffer();
console.log(new Uint8Array(buffer));
// Uint8Array(11) [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
从缓存中检索
如需在缓存中查找项,您可以使用 match
方法。
const response = await cache.match(request);
console.log(request, response);
如果 request
是一个字符串,浏览器会通过调用 new Request(request)
将其转换为 Request
。如果找到匹配条目,该函数会返回解析为 Response
的 Promise
,否则返回 undefined
。
为了确定两个 Requests
是否匹配,浏览器不仅会使用网址,如果两个请求具有不同的查询字符串、Vary
标头或 HTTP 方法(GET
、POST
、PUT
等),则将其视为不同的请求。
您可以通过传递一个选项对象作为第二个参数来忽略部分或全部内容。
const options = {
ignoreSearch: true,
ignoreMethod: true,
ignoreVary: true
};
const response = await cache.match(request, options);
// do something with the response
如果有多个缓存请求匹配,则返回最先创建的请求。如果要检索所有匹配的响应,可以使用 cache.matchAll()
。
const options = {
ignoreSearch: true,
ignoreMethod: true,
ignoreVary: true
};
const responses = await cache.matchAll(request, options);
console.log(`There are ${responses.length} matching responses.`);
作为一种快捷方式,您可以使用 caches.match()
一次搜索所有缓存,而不必为每个缓存调用 cache.match()
。
正在搜索
除了针对 Response
对象匹配条目之外,Cache API 不提供搜索请求或响应的方式。不过,您可以使用过滤或创建索引来实现自己的搜索。
过滤
实现自定义搜索的一种方法是遍历所有条目并过滤出所需的条目。假设您想要查找网址以 .png
结尾的所有项。
async function findImages() {
// Get a list of all of the caches for this origin
const cacheNames = await caches.keys();
const result = [];
for (const name of cacheNames) {
// Open the cache
const cache = await caches.open(name);
// Get a list of entries. Each item is a Request object
for (const request of await cache.keys()) {
// If the request URL matches, add the response to the result
if (request.url.endsWith('.png')) {
result.push(await cache.match(request));
}
}
}
return result;
}
这样,您就可以使用 Request
和 Response
对象的任何属性来过滤条目。请注意,如果搜索大量数据,速度会很慢。
创建索引
实现自定义搜索的另一种方法是维护可以搜索的条目的单独索引,并将该索引存储在 IndexedDB 中。因为 IndexedDB 是专为这种操作而设计的,所以在处理大量条目时,它的性能会大大提升。
如果您将 Request
的网址与可搜索属性一起存储,则可以在执行搜索后轻松检索正确的缓存条目。
删除项目
如需从缓存中删除某项内容,请执行以下操作:
cache.delete(request);
其中,请求可以是 Request
,也可以是网址字符串。此方法还采用与 cache.match
相同的选项对象,允许您删除同一网址的多个 Request
/Response
对。
cache.delete('/example/file.txt', {ignoreVary: true, ignoreSearch: true});
删除缓存
如需删除缓存,请调用 caches.delete(name)
。如果缓存存在且已被删除,此函数会返回一个解析为 true
的 Promise
,否则返回 false
。
此致
感谢撰写了本文的原始版本(首次发布在 WebFundamentals)的 Mat Scales。