Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Querystring to avoid IE caching

It is a well known problem that IE caches too much of html, even when giving a Cache-Control: no-cache or Last-Modified header to everypage.

This behaiviour is really troubling when working with querystrings to get dynamic information, as IE considers it to be the same page (i.e.: http://example.com/?id=10) and serves the cached version.

I've solved it adding either a random number or a timestring to the querystring (as others have done) like this http://example.com/?id=10&t=2009-08-06_13:12:56 that I just ignore serverside.

Is there a better option? Is there another, cleaner way to acomplish this? I'm aware that POST isn't cached, but it is semanticaly correct to use GET here.

like image 473
Esteban Küber Avatar asked Aug 05 '09 16:08

Esteban Küber


4 Answers

Assuming you are using jQuery, instead of using $.get or $.getJson, use the more generic $.ajax and explicitly set the cache value to false. The following is an example:

$.ajax({
        url: "/Controller/Action",
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data, textStatus) {
                         alert("success");
                 }
    });

A little more code required (not much though) than using .getJson or .get but will solve the problem cleanly without appending random numbers.

like image 87
Simon Fox Avatar answered Oct 31 '22 19:10

Simon Fox


You could also use the current Unix Time in milliseconds to avoid the problem of many requests in one second (it is much less likely to have multiple requests in one millisecond)

var url = "http://whatever.com/stuff?key=value&ie=" + (new Date()).getTime();
like image 25
Sinan Taifour Avatar answered Oct 31 '22 21:10

Sinan Taifour


Using a random number (not timestamp) on the querystring, or actually changing the filename are the two methods recommended. Steve Souders and YAHOO!'s performance group has published a ton of useful information and practices they've discovered and developed while optimizing one of the world's most heavily-visited properties.

like image 2
Rex M Avatar answered Oct 31 '22 19:10

Rex M


So, in the end, the only reliable way to do this (thanks to IE6) is using a random, or time bound querystring.

You could use a time bound querystring that only changes every 15 seconds (or any other amount of time), so you'd lower the server hit count, as you'd see locally cached content for those 15 seconds.

If you have a standard compliant browser, you can get away with only using ETags.

like image 2
Esteban Küber Avatar answered Oct 31 '22 21:10

Esteban Küber