views:

43

answers:

2

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.

+1  A: 

You need a plug-in to do this. Firebug can tell you on the "NET" tab, once you install it (for Firefox). JavaScript itself cannot see the browser's HTTP traffic.

Diodeus
As I mention in the question, I'm doing client-side instrumentation on real pageviews. It is unlikely that I will get a lot of our users to install Firebug, especially the ones who don't use Firefox.
William Pietri
Not liking the truth is no reason for a down-vote. Thanks. :(
Diodeus
Your answer could be fine on a different question, but it's unhelpful here. Making sure the most helpful answer is at the top of the page seems a reasonable use of up- and down-voting to me.
William Pietri
+1  A: 

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.

Annie
Thanks, Annie. That makes perfect sense. Some browsers are weird when you mix script blocks and loading external resources, so this may impact parallel downloads; I'll try it and see.
William Pietri
Annie