How To Check If A Resource Is Cached By The Browser From Javascript?
Solution 1:
You 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:
asynccheckImageCached(url, waitTimeMs = 4) {
const ac = newAbortController()
const cachePromise = fetch(url, {signal: ac.signal})
.then(() =>true)
.catch(() =>false)
setTimeout(() => ac.abort(), waitTimeMs)
return cachePromise
}
Solution 2:
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');
} elseif (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.
Post a Comment for "How To Check If A Resource Is Cached By The Browser From Javascript?"