翻译正在进行中。

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

Cache 接口提供缓存的 Request / Response 对象对的存储机制,例如作为ServiceWorker 生命周期的一部分。 Cache 接口像 workers 一样, 是暴露在 window 作用域下的。尽管它被定义在 service worker 的标准中,  但是它不必一定要配合 service worker 使用.

一个域可以有多个 Cache 对象.  你将在你的代码中处理和更新缓存 (e.g. in a ServiceWorker) . 在 Cache 除非显示地更新缓存, 否则缓存将不会被更新; 缓存数据不会过期, 除非删除它. 使用 CacheStorage.open(cacheName) 打开一个Cache 对象, 再使用 Cache 对象的方法去处理缓存.

你需要定期地清理缓存条目, 因为每个浏览器都严格限制了一个域下缓存数据的大小. 浏览器尽其所能去管理磁盘空间, 浏览器有可能去删除一个域下的缓存数据.   确保你的代码可以安全地操作缓存. 查看 Deleting old caches 获取更多信息.

Note: Cache.putCache.add, and Cache.addAll only allow GET requests to be stored in the cache.

Note: Initial Cache implementations (in both Blink and Gecko) resolve Cache.add, Cache.addAll, and Cache.put promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

Note: As of Chrome 46, the Cache API will only store requests from secure origins, meaning those served over HTTPS.

Note: The key matching algorithm depends on the VARY header in the value. So matching a new key requires looking at both key and value for entries in the Cache.

Note: The caching API doesn't honor HTTP caching headers.

Methods

Cache.match(request, options)
Returns a Promise that resolves to the response associated with the first matching request in the Cache object.
Cache.matchAll(request, options)
Returns a Promise that resolves to an array of all matching requests in the Cache object.
Cache.add(request)
Takes a URL, retrieves it and adds the resulting response object to the given cache. This is fuctionally equivalent to calling fetch(), then using Cache.put() to add the results to the cache.
Cache.addAll(requests)
Takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache.
Cache.put(request, response)
Takes both a request and its response and adds it to the given cache.
Cache.delete(request, options)
Finds the Cache entry whose key is the request, and if found, deletes the Cache entry and returns a Promise that resolves to true. If no Cache entry is found, it returns false.
Cache.keys(request, options)
Returns a Promise that resolves to an array of Cache keys.

Examples

This code snippet is from the service worker selective caching sample. (see selective caching live) The code uses CacheStorage.open(cacheName) to open any Cache objects with a Content-Type header that starts with font/.

The code then uses Cache.match(request, options) to see if there's already a matching font in the cache, and if so, returns it. If there isn't a matching font, the code fetches the font from the network and uses Cache.put(request, response) to cache the fetched resource.

The code handles exceptions thrown from the fetch() operation. Note that a HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name. The code also deletes all caches that aren't named in CURRENT_CACHES.

Note: In Chrome, visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing.
var CACHE_VERSION = 1;

// Shorthand identifier mapped to specific versioned cache.
var CURRENT_CACHES = {
  font: 'font-cache-v' + CACHE_VERSION
};

self.addEventListener('activate', function(event) {
  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  // Active worker won't be treated as activated until promise resolves successfully.
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (expectedCacheNames.indexOf(cacheName) == -1) {
            console.log('Deleting out of date cache:', cacheName);
            
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(
    
    // Opens Cache objects that start with 'font'.
    caches.open(CURRENT_CACHES['font']).then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log(' Found response in cache:', response);

          return response;
        } 
      }).catch(function(error) {
        
        // Handles exceptions that arise from match() or fetch().
        console.error('  Error in fetch handler:', error);

        throw error;
      });
    })
  );
});

Specifications

Specification Status Comment
Service Workers
Cache
Working Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40.0 39 (39)[1] 未实现 24 未实现
add() 44.0 (Yes)[1] ? ? ?
addAll() 46.0 (Yes)[1] ? ? ?
matchAll() 47.0 (Yes)[1] ? ? ?
Require HTTPS for add(), addAll(), and put() 46.0 (Yes)[1] ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support 未实现 未实现 39.0 (39) ? 未实现 ? 未实现 40.0
add() 未实现 未实现 (Yes) ? ? ? ? 44.0
addAll() 未实现 未实现 (Yes) ? ? ? ? 46.0
matchAll() 未实现 未实现 (Yes) ? ? ? ? 46.0
Require HTTPS for add(), addAll(), and put() 未实现 未实现 (Yes) ? ? ? ? 46.0

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

See also

文档标签和贡献者

 此页面的贡献者: ChauMing, huaguhzheng, xgqfrms-GitHub, jpmedley
 最后编辑者: ChauMing,