4

Is it possible to determine that the loaded web resources like css, jscript, images, even the html itself are coming from cache or not using javascript ?

I'm trying to create a simple report on those loaded resources directly on on every pages i access in my development mode to avoid having to open up my google chrome debug tool every single time.

Bertie
  • 17,277
  • 45
  • 129
  • 182

2 Answers2

0

Though there are no direct way to figure out this using javascript, we can use a dirty workaround using windows.performance javascript API. Example given below

var fileToLookup = "http://sample.com/img/loader.png";
var isCached = Boolean(_.filter(window.performance.getEntries(),function(a){ return a.duration > 0 && a.name == fileToLookup }).length) 

Here we are iterating the resources referred by the page and filtering by duration. If a resource taking > 0ms, we are assuming as not cached. Again, this is not foolproof method.

Sriram
  • 767
  • 2
  • 17
  • 42
  • I'm doing `window.performance.getEntriesByName("resource.js")[0].duration` on my website and the duration is always bigger than 0, even for resources that came with proper `cache-control` header. I mean, they should be cached – Andre Pena Feb 20 '20 at 13:48
  • For example, you can try this on Stackoverflow: `window.performance.getEntriesByName("https://www.google-analytics.com/analytics.js")[0].duration`. It is not zero – Andre Pena Feb 20 '20 at 13:50
  • I figured you should just use `transferSize`. See my answer. – Andre Pena Feb 20 '20 at 15:23
  • @AndrePena transferSize can also be zero when CORS restrictions are there and values are not allowed to be read – Tushar Shahi Nov 29 '22 at 09:59
-3

There are many solution to prevent the browser cache the resource, such as:

  1. version number in filename (simple way for programmer, and not system admin)
  2. Modify the Apache ETags

You can add a resource version number after the file name. Every time you modified the media file (Images/JS/CSS), you update the resource version.

<?php $resourceVer = '201404151859'; ?>
<script src='scripts/main.js?v=<?=$resourceVer?>'></script>
<link rel='stylesheet' href='style/main.css?v=<?=$resourceVer?>' />

Goal: the ?v=201404151859 is fake the browser there are different document of main.js, main.js?v=201404151859

Allen Chak
  • 1,802
  • 1
  • 10
  • 21
  • 1
    While your answer contains factual information, it does not address the question as posed. It _forces_ the download of the resources, rather than _reporting_ whether they were loaded from the cache or not. My -1. – enhzflep Apr 15 '14 at 11:30