这篇翻译不完整。请帮忙从英语翻译这篇文章

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

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

通常,你只想 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);
})

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

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

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

语法

cache.put(request, response).then(function() {
  // request/response pair has been added to the cache
});

参数

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');
});

规范

Specification Status Comment
Service Workers
Cache
Working Draft Initial definition.

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support43116392 No303 No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support431431 No39303 No4.0

1. Requires HTTPS from version 46.

2. Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR).

3. Requires HTTPS from version 33.

See also

文档标签和贡献者

此页面的贡献者: flyingsouthwind
最后编辑者: flyingsouthwind,