CacheStorage.has()

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 接口的 has() 方法返回一个 Promise 对象,其在 Cache 对象有 cacheName 时兑现为 true

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

语法

js
has(cacheName)

参数

cacheName

一个表示你正在 CacheStorage 中查找的 Cache 对象 name 的 DOMString.

返回值

一个 Promise 对象,缓存存在时兑现为 true,否则兑现为 false

示例

在下面的例子中首先检测是否有名为 v1 的缓存存在,如果存在我们会向其添加内容,如果不存在我们会做些对应的初始化动作。

js
caches
  .has("v1")
  .then(function (hasCache) {
    if (!hasCache) {
      someCacheSetupfunction();
    } else {
      caches.open("v1").then(function (cache) {
        return cache.addAll(myAssets);
      });
    }
  })
  .catch(function () {
    // 处理异常
  });

规范

Specification
Service Workers
# cache-storage-has

浏览器兼容性

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
has

Legend

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

Full support
Full support

参考