Search code examples
javascriptcachingoptimizationwebpackcdn

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.


Solution

  • 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