Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 856
Seaskyways Avatar asked Oct 24 '25 03:10

Seaskyways


1 Answers

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:

      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
      }
like image 85
Seaskyways Avatar answered Oct 26 '25 17:10

Seaskyways



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!