Wednesday 27 January 2010

IE AJAX Caching Issue

I don't want to pick on IE again (it has been less than 24 hours since my last post about IE), but I'm afraid I have to. I've been working on a new project recently that makes use of AJAX. I usually develop in Firefox and then fix all my IE problems afterwards. This time however one of my AJAX areas of the site seemed to rarely update in IE (if at all), other browsers were fine.

After some playing around I came to the conclusion that IE was caching my AJAX requests. You could argue that IE is right to cache the requests, as the HTTP spec states that GET requests should be cached. But given the browser knows a XMLHttpRequest is being made the caching is completely uneccessary/unwanted. Once I knew the problem the fix was easy. I just needed to append something random to the request URI, a number or timestamp for example.

So instead of requests to /Resource, just use /Resource?ie={random}. It's fairly straight forward to generate a random number in Javascript:


// Random number between 0 and 100
Math.floor(Math.random()*101);


Realising that I wouldn't be alone in tackling the issue I found people used similar tactics to get around the problem. Another neat way is to change the request to be a POST.

1 comment:

  1. If you're using JQuery to make the AJAX call you can use

    $.ajaxSetup({ cache: false });

    to do the same thing.

    ReplyDelete