Refreshing an image when filename is the same

Here’s a nifty little trick that might get you out of a bind:

Say you have a web app in which the user can change the images by uploading new image files. Say then that the application requires that the image filename remain the same. See the problem?

The image may have changed but your browser is still looking at the same filename, so it will display its cached image. Of course, you could try an edit your HTML to that caching doesn’t occur, but we like caching, so here’s a better solution.

An image file, like a script file, can accept an argument when requested with HTTP. For instance, the image below is requested so:

<IMG src=/blog/wp-content/pottery-main.thumbnail.jpg?foo>

The cool thing about this is that you attach random arguments to your image calls, either in HTML or in Javascript, which will cause the browser to reload that image every time it is called. Hence, when your user loads a new image, and this image has the same file name as the old image, this method will allow the user to view the new image without having to do a manual refresh.

In Javascript, you can create a random argument using time and date functions. e.g.

my_image.src=”images/pottery.jpg?” + (new Date()).getTime();


image_td.innerHTML = “<IMG src=images/pottery.jpg?” + (new Date()).getTime() + “</IMG>”;