admin管理员组文章数量:1356904
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.
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.
Share Improve this question asked Jan 17, 2020 at 12:37 SeaskywaysSeaskyways 3,7953 gold badges31 silver badges44 bronze badges2 Answers
Reset to default 4You can leverage the fetch
API and it's correspondent AbortController
to achieve this functionality with a margin of error (expected false negatives).
It goes like this, fetch
the required resource with a signal attached. Abort in a small amount of time eg. 4ms. 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):
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.
本文标签: cachingHow to check if a resource is cached by the browser from JavascriptStack Overflow
版权声明:本文标题:caching - How to check if a resource is cached by the browser from Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744031811a2579048.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论