How can I use JavaScript to detect if I am on a cached page

With the new Resource Timing Level 2 spec you can use the transfer size property to check if the page is loaded from cache:

var isCached = performance.getEntriesByType("navigation")[0].transferSize === 0;
  • Spec: https://www.w3.org/TR/resource-timing-2/#dom-performanceresourcetiming-transfersize
  • Browser support: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming#Browser_compatibility
    • note that at the time of writing, it shows Safari does not support while in actuality the latest version does.

I started with the answer "Daniel" gave above but I fear that over a slow connection I could run into some latency issues.

Here is the solution that ultimately worked for me. On the server side I add a cookie refCount and set it's value to 0. On document load in javascript I first check refCount and then increment it. When checking if refCount is greater than 1 I know the page is cached. So for this works like a charm.

Thanks guys for leading me to this solution.


One way you could do it is to include the time the page was generated in the page and then use some javascript to compare the local time to the time the page was generated. If the time is different by a threshold then the page has come from a cache. The problem with that is if the client machine has its time set incorrectly, although you could get around this by making the client include its current system time in the request to generate the page and then send that value back to the client.

Tags:

Javascript