How can I tell when a web page resource is cached?
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.
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.