Friday, January 27, 2012

In Which I Stop IE 8 Caching Images

I'm not a fan of IE, I'll say that now. Things like the lack of Javascript error feedback (which may have changed with IE9) and the inability to view generated source (again, may have changed) really annoy me. I can code HTML standard pages with Javascript & CSS which work in all other browsers with no 'special' things needed, but they suddenly require a raft of hacks for IE. One thing I have just come across is image caching. I have a page which displays a list of images. I can then bring up an iframed image uploader which resizes images and then refreshes the image display. This works everywhere. Except in IE, where it just shows the original (unchanged) image. 'Aha' I thought - caching, I know, I'll add the good ol' cache prevention stuff, like
This blog posting and even using the meta tags as described in Microsoft's own knowledge base. No joy, same ol' images appearing. It looks like IE doesn't regard images as the property of caches, and stores them in it's own image cache which completely ignores any of those silly 'Do not bloody cache' indicators.

The only way to prevent the caching appears to be to rename your image each time, which is a right royal pain in the codebase, so what's a boy to do? That question mark just there appears to be the answer. I knew that things like Dojo add cache prevention in Ajax by adding a timestamp. Just as an experiment I added a timestampt to an img src attribute (my images are dynamically created by either JS or PHP). Hey presto, it works!

In Javascript I just did:
var imgName = "foo/bar.png";
var time = new Date().getTime();
img.setAttribute("src",imgName+"?"+time);

Whereas in php I just did:
<?php
echo "<img src=\"foo/bar.png?\"".time()."\"/>";
?>
It seems to work in everything I've tried, and has made me quite a happy bunny