tags:

views:

379

answers:

4

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?

+5  A: 

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.

Daniel
damn, you beat me to it, thumbs up!
Bogdan
I was actually thinking of this solution. I was hoping something easier in the document but maybe it does not exist :)
Jamey McElveen
A: 

Not directly, their may be some browsers that have some custom command that allows it.

There is a work around that would do what you want. Use a cookie of the time first visit and then use the META HTTP-EQUIV to set the length of time the file is cached. If the current time is within the time period of the cookie and the length of cache expiration then treat as if they loaded from cache. One the cache has expired reset the cookie time.

Will Dieterich
A: 

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Allain Lalonde
I was about to suggest the same thing, but the question indicates that he wants to see whether the currently loaded page is cached, if you fire an XHR off, then that would be indicative of the next request, not the current one.
Heat Miser
Thanks, I cannot use this but, the link you sent me helps me with another issue.
Jamey McElveen
+2  A: 

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 java script 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.

Jamey McElveen
I've used the same approach myself. I wrote up a detailed description on my blog:http://monket.net/blog/2010/02/detecting-when-a-page-is-loaded-from-the-browser-cache/
Karl