大网数据广告活动
Web 标准与前端开发

Cache.put()

· 52CE 我爱测

Cache 接口的 **`put()`** 方法 允许将键/值对添加到当前的 Cache 对象中。

Service Workers API

Cache 接口的 put() 方法 允许将键/值对添加到当前的 Cache 对象中。

通常,你只想 GloblFetch.fetch 一个或多个请求,然后直接添加结果到 cache 中。这种情况下,最好使用 Cache.add/Cache.addAll,因为它们是一个或者多个这些操作的便捷方法。

fetch(url).then(function (response) {
  if (!response.ok) {
    throw new TypeError("Bad response status");
  }
  return cache.put(url, response);
});

[!NOTE] put() 将覆盖先前存储在匹配请求的 cache 中的任何键/值对。

[!NOTE] Cache.add/Cache.addAll 不会缓存 Response.status 值不在 200 范围内的响应,而 Cache.put 允许你存储任何请求/响应对。因此,Cache.add/Cache.addAll 不能用于不透明的响应,而 Cache.put 可以。

[!NOTE] 当响应主体完全写入磁盘时,初始 Cache 执行 (在 Blink 和 Gecko 中) resolve Cache.add、Cache.addAll 和 Cache.put promise. 更新的规范版本中声明:即使响应主体仍在流式传输,一旦条目被记录到数据库中,浏览器就可以 resolve promise.

语法

put(request, response)

参数

  • request
    • : The Request you want to add to the cache.
  • response
    • : The Response you want to match up to the request.

返回值

A Promise that resolves with void.

[!NOTE] The promise will reject with a TypeError if the URL scheme is not http or https.

示例

This example is from the MDN sw-test example (see sw-test running live). Here we wait for a FetchEvent to fire. We construct a custom response like so:

  1. Check whether a match for the request is found in the CacheStorage using CacheStorage.match. If so, serve that.
  2. If not, open the v1 cache using open(), put the default network request in the cache using Cache.put and return a clone of the default network request using return response.clone(). Clone is needed because put() consumes the response body.
  3. If this fails (e.g., because the network is down), return a fallback response.
var response;
var cachedResponse = 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");
  });

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。