Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Caching of AJAX results in IE8

IE is notorious for its aggressive caching of Ajax responses. As you're using jQuery, you can set a global option:

$.ajaxSetup({
    cache: false
});

which will cause jQuery to add a random value to the request query string, thereby preventing IE from caching the response.

Note that if you have other Ajax calls going on where you do want caching, this will disable it for those too. In that case, switch to using the $.ajax() method and enable that option explicitly for the necessary requests.

See http://docs.jquery.com/Ajax/jQuery.ajaxSetup for more info.


As marr75 mentioned, GET's are cached.

There are a couple of ways to combat this. Aside from modifying the response header, you can also append a randomly generated query string variable to the end of the targeted URL. This way, IE will think it is a different URL each time it is requested.

There are multiple ways to do this (such as using Math.random(), a variation on the date, etc).

Here's one way you can do it:

var oDate = new Date();
var sURL = "/game/getpuzzleinfo?randomSeed=" + oDate.getMilliseconds();
$.get(sURL, null, function(data, status) {
    // your work
});

Gets are always cacheable. One strategy that may work is to edit the response header and tell the client to not cache the information or to expire the cache very soon.


If you are calling ashx page you can also disable caching on the server with the following code:

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); 

this is what i do for ajax calls:

var url = "/mypage.aspx";
// my other vars i want to add go here
url = url + "&sid=" + Math.random();
// make ajax call

it works pretty well for me.


NickFitz gives a good answer, but you'll need to turn the caching off in IE9 as well. In order to target just IE8 and IE9 you could do this;

<!--[if lte IE 9]>
<script>
    $.ajaxSetup({
        cache: false
    });
</script>
<![endif]-->