Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell when a web page resource is cached?

Is there a way in JavaScript for me to tell whether a resource is already in the browser cache?

We're instrumenting a fraction of our client-side page views so that we can get better data on how quickly pages are loading for our users. The first time users arrive on our site, a number of resources (JS, CSS, images) are cached by the browser, so their initial pageview is going to be slower than subsequent ones.

Right now, that data is mixed together, so it's hard to tell an initial page load from a subsequent pageview that's slow for some other reason. I'd love a cross-browser way to check to see whether the cache is already primed, so that I can segregate the two sorts of pageview and analyze them separately.

like image 657
William Pietri Avatar asked Mar 02 '10 22:03

William Pietri


2 Answers

You should use TransferSize:

window.performance.getEntriesByName("https://[resource-name].js")[0].transferSize

To verify it, you can run the above line on Chrome...

  • If the browser has caching enabled and your resource was previously loaded with proper cache-control header, transferSize should be 0.
  • If you disable caching (Network tab -> Disable cache) and reload, transferSize should be > 0.
like image 71
André Pena Avatar answered Sep 17 '22 13:09

André Pena


There isn't a JavaScript API for checking if a resource is cached. I think the best you can do is check how long it took to load the resources, and bucket the ones with shorter load times together.

At the top of the page:

<script>var startPageLoad = new Date().getTime();</script>

On each resource:

<img src="foo.gif" onload="var fooLoadTime = startPageLoad - new Date().getTime()">
<script src="bar.js" onload="var barLoadTime = startPageLoad - new Date().getTime()">

When reporting load times:

var fooProbablyCached = fooLoadTime < 200; // Took < 200ms to load foo.gif
var barProbablyCached = barLoadTime < 200; // Took < 200ms to load bar.gif

You may need to use onreadystatechange events instead of onload in IE.

like image 39
Annie Avatar answered Sep 19 '22 13:09

Annie