Cache:put() 方法
注意:此功能在 Web Workers 中可用。
Cache 接口的 put() 方法允许将键/值对添加到当前的 Cache 对象。
通常,您只想 fetch() 一个或多个请求,然后将结果直接添加到您的缓存中。在这种情况下,您最好使用 Cache.add()/Cache.addAll(),因为它们是一个或多个这些操作的简写函数。
js
fetch(url).then((response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
注意:put() 会覆盖缓存中先前存储的与请求匹配的任何键/值对。
注意: Cache.add/Cache.addAll 不会缓存 Response.status 值不在 200 范围内的响应,而 Cache.put 允许您存储任何请求/响应对。因此,Cache.add/Cache.addAll 不能用于存储不透明响应,而 Cache.put 可以。
语法
js
put(request, response)
参数
返回值
一个 Promise,解析为 undefined。
异常
TypeError-
如果 URL 方案不是
http或https,则返回此值。
示例
此示例来自 MDN 的 simple-service-worker 示例(请参阅 正在运行的 simple-service-worker 实时示例)。在这里,我们等待 FetchEvent 触发。我们像这样构造一个自定义响应:
- 使用
CacheStorage.match()检查是否在CacheStorage中找到请求的匹配项。如果找到,则提供该匹配项。 - 如果没有找到,则使用
open()打开v1缓存,使用Cache.put()将默认网络请求放入缓存,并使用return response.clone()返回默认网络请求的克隆。需要克隆,因为put()会消耗响应体。 - 如果失败(例如,因为网络中断),则返回一个备用响应。
js
let response;
const cachedResponse = caches
.match(event.request)
.then((r) => (r !== undefined ? r : fetch(event.request)))
.then((r) => {
response = r;
caches.open("v1").then((cache) => cache.put(event.request, response));
return response.clone();
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));
规范
| 规范 |
|---|
| Service Workers # cache-put |
浏览器兼容性
加载中…