Thursday, November 24, 2005

Cache-Busting with Javascript

Got an opportunity to work with Javascript. On reading, got this information.

What it is?

As we all know, when we are browsing the pages fetched by the browser will be stored in the browser's cache. If we want to get the page from the server and not from the cache, using Javascript, it is very simple. Just add a random key-value pair to the URL. This should be unique for each request.

How to do?
Set your request URL as :
URL +"?rand=" + (Math.random() * 99999999);

How it works?

I assume that, the browser MAY maintain a key-value pair (Something like a HashTable), that contains the "URL of the requested page" as the key and the "contents of the page" as its value. So when a request is made, it first checks its cache and if it finds a page it returns it, else fetches from the server. In our case, since random() generates different values for each call, the browser will assume that this is a new request for a page and fetches it from the server. This in no way affect the server. Since the server may not know about the additional parameter, it will discard the variable.

2 comments:

Unknown said...

does this also mean that someone else can retreive your mail? when I send an email, it has in it: please place your redirects in front of the value. at the end it says cache bust string.

Mani said...

I didn't get the clear context of the background. Can you explain?

One thing for sure is, only people who knows my password can access my mail. Once you login a session with an unique id is created by the server. This will be passed along with the user's request. Based on the session id, the contents will be displayed.