Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. Cache
  4. Cache.put()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Cache.put()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2018年4月⁩.

实验性:这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

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

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

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

备注:put() 将覆盖先前存储在匹配请求的 cache 中的任何键/值对。

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

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

语法

js
put(request, response)

参数

request

TheRequest you want to add to the cache.

response

TheResponse you want to match up to the request.

返回值

APromise that resolves with void.

备注:The promise will reject with aTypeError if the URL scheme is nothttp orhttps.

示例

This example is from the MDNsw-test example (seesw-test running live). Here we wait for aFetchEvent to fire. We construct a custom response like so:

  1. Check whether a match for the request is found in theCacheStorage usingCacheStorage.match(). If so, serve that.
  2. If not, open thev1 cache usingopen(), put the default network request in the cache usingCache.put() and return a clone of the default network request usingreturn response.clone(). Clone is needed becauseput() consumes the response body.
  3. If this fails (e.g., because the network is down), return a fallback response.
js
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");  });

规范

Specification
Service Workers Nightly
# cache-put

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp