简体   繁体   English

如何检查资源是否被浏览器从 Javascript 缓存?

[英]How to check if a resource is cached by the browser from Javascript?

Is there a way to check if a resource is cached by the browser without downloading the resource?有没有办法在不下载资源的情况下检查资源是否被浏览器缓存? Most of the questions and answers are old and I believe things have changed now and there are better ways.大多数问题和答案都是旧的,我相信现在情况已经发生了变化,并且有更好的方法。

You can leverage the fetch API and it's correspondent AbortController to achieve this functionality with a margin of error (expected false negatives).您可以利用fetch API 及其对应的AbortController来实现此功能,但有一定的误差(预期的漏报)。

It goes like this, fetch the required resource with a signal attached.它是这样的,通过附加信号fetch所需的资源。 Abort in a small amount of time eg.在短时间内中止,例如。 4ms. 4 毫秒。 If the fetch is returned in the short amount of time it's absolutely cached.如果在短时间内返回获取,则它绝对被缓存。 If the fetch was aborted, it's probably not cached.如果提取被中止,它可能没有被缓存。 Here's some code:这是一些代码:

      async checkImageCached(url, waitTimeMs = 4) {
        const ac = new AbortController()
        const cachePromise = fetch(url, {signal: ac.signal})
          .then(() => true)
          .catch(() => false)
        setTimeout(() => ac.abort(), waitTimeMs)
        return cachePromise
      }

Currently only works on Firefox, unfortunately, but another option is to use only-if-cached , though it only works for requests on the same origin (because it requires mode: 'same-origin' as well):不幸的是,目前仅适用于 Firefox,但另一种选择是使用only-if-cached ,尽管它仅适用于同一来源的请求(因为它也需要mode: 'same-origin' ):

fetch(urlOnSameOrigin, { mode: 'same-origin', cache: 'only-if-cached'})
  .then((response) => {
    if (response.ok) {
      console.log('Cached');
    } else if (response.status === 504) {
      console.log('Not cached');
    }
  })
  .catch(() => {
    console.log('Network error');
  });

only-if-cached — The browser looks for a matching request in its HTTP cache. only-if-cached — 浏览器在其 HTTP 缓存中查找匹配的请求。

  • If there is a match, fresh or stale, it will be returned from the cache.如果有匹配项,无论是新鲜的还是陈旧的,都将从缓存中返回。

  • If there is no match, the browser will respond with a 504 Gateway timeout status.如果不匹配,浏览器将响应 504 网关超时状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM