Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I want to display from cache for a long time and I want a slightly different behavior on page render vs loading the page from cache. Is there an easy way I can determine this with JavaScript?

like image 494
Jamey McElveen Avatar asked Nov 03 '08 21:11

Jamey McElveen


People also ask

How can I tell if a Web page is cached?

In Google's search box, type the website or page you're trying to see. Beside the URL, click the down arrow. Select "Cached". You are now viewing the cached page.

Can JavaScript read cache?

There is no way to read the cache manually - it all happens behind the scenes, if there is cache. Yes, you can store the website's source code to the browser cache, but only the client-side part - HTML/CSS/JS/images/fonts/etc.

How do you check if JS is cached?

If you have Chrome, open the Inspector (right-click, "Inspect Element"), then click the Network tab. Now reload the page. You should see a list of all of the elements that were loaded for the page. To determine if the Javascript (or any element) was cached, what you want to look for is the "Size" column.


2 Answers

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.

like image 176
Jamey McElveen Avatar answered Sep 19 '22 14:09

Jamey McElveen


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.

like image 38
Daniel Avatar answered Sep 19 '22 14:09

Daniel