thedarklord47
thedarklord47

Reputation: 3302

Javascript: Any way to check if an asset is present in browser cache?

I am trying to optimize my webpack bundle sizes. Looking at my vendor bundle, the largest chunk is ReactDOM + React.

I was thinking I could take advantage of webpack's externals config option to let a CDN serve these assets as I am currently doing with jQuery. I checked though and my personal browser did not have these assets cached, so I began to wonder if others would. If most people don't have these assets already cached, loading them externally would do more harm than good due to the extra round trips.

Anyone know of a cross browser solution for checking if an asset is currently cached? This way I could generate some analytics on my user base to see if externalizing these larger assets would be a good move.

I have seen the Cache API for most modern browsers. I still need a solution for Safari/IE, though.

Upvotes: 1

Views: 2468

Answers (2)

Sujoy Chatterjee
Sujoy Chatterjee

Reputation: 51

You may use the Resource Timing API to find all the resources that were loaded and the transferSize property of each resource to know if it was loaded from cache. A transfer size of 0 indicates cached load. Anything more than 0 indicates actual transfer through the network and hence uncached resource.

const resourcesStatus = window.performance.getEntriesByType('resource')
  .reduce(function(formattedOutput, resourceDetails) {
    return formattedOutput.concat({
      resourceName: resourceDetails.name,
      cached: resourceDetails.transferSize ? false : true
    })}, [])

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

Due to the fact that script files are loaded in order you could just take the time before and after reacts include. If that time is below a few milliseconds, it comes from cache and the time is just what it takes to parse, otherwise it was loaded from a server and ypu got network latency:

<script>
  var start = Date.now();
 </script>
 <script src="cdn/react.min.js" ></script>
 <script>
   var loadTime = Date.now() - start;
   // Do whatever with that
   if(loadTime < 10) alert("cached");
</script>

You probably get false positives and negatives with very slow browsers and high speed users though

Upvotes: -1

Related Questions