CacheStorage.open()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性在 Web Worker 中可用。

CacheStorage 接口的 open() 方法返回一个兑现为匹配 cacheNameCache 对象的 Promise

你可以通过窗口的 Window.caches 属性或 worker 的 WorkerGlobalScope.caches 属性访问 CacheStorage

备注: 如果指定的 Cache 不存在,则使用该 cacheName 创建一个新的缓存,并返回一个兑现为这个新的 Cache 对象的 Promise

语法

js
open(cacheName)

参数

cacheName

要打开的缓存对象的名称。

返回值

一个会兑现为请求的 Cache 对象的 Promise

示例

此示例来自于 MDN service worker 简单示例(请参阅在线的 service worker 简单示例)。这里,等待 FetchEvent 事件触发,然后运行 waitUntil() 来处理应用的安装。这包括调用 CacheStorage.open() 来创新新的缓存,然后使用 Cache.addAll() 向其中添加一系列资源。

js
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});

规范

Specification
Service Workers
# cache-storage-open

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
open

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见