是否可以在不下载资源的情况下检查浏览器是否缓存了资源?大多数问题和答案都是古老的,我相信现在情况已经改变,并且有更好的方法。
您可以利用fetch
API及其对应的AbortController
来实现此功能,并留有一定的误差(预期的假阴性)。
就像这样,fetch
附加了信号的所需资源。在短时间内中止,例如。 4毫秒如果在短时间内返回获取,则将对其进行绝对缓存。如果提取被中止,则可能不会被缓存。这是一些代码:
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
}
[不幸的是,当前它仅在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'); });
仅当缓存时-浏览器在其HTTP缓存中查找匹配的请求。
如果有匹配项,新鲜的或过期的,将从缓存中返回。
如果不匹配,浏览器将以504网关超时状态进行响应。