如何检查Javascript中的资源是否被浏览器缓存?
How to check if a resource is cached by the browser from Javascript?
有没有办法在不下载资源的情况下检查资源是否被浏览器缓存?大多数问题和答案都是旧的,我相信现在情况已经发生了变化,并且有更好的方法。
您可以利用 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');
});
only-if-cached — The browser looks for a matching request in its HTTP cache.
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.
有没有办法在不下载资源的情况下检查资源是否被浏览器缓存?大多数问题和答案都是旧的,我相信现在情况已经发生了变化,并且有更好的方法。
您可以利用 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');
});
only-if-cached — The browser looks for a matching request in its HTTP cache.
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.