How do I force an image to reload on a web page?

It’s easy to make an image reload just by refreshing a page in your browser. Reloading just the image without forcing the whole page to refresh is a little trickier.

This is a useful technique to use if you have a rotating image that you would like to cycle every few seconds, or for a site that does photo editing and shows the effects to the user in real time.

Here is a simple way of doing this in Javascript:

function reloadImage() {
_ if (document.images) {_
_ var now = new Date();_
_ document.images.randimg.src = “/randimg?” + now.getTime();_
_ setTimeout(“reloadImage()”, 5000);_
_ }_
}
setTimeout(“reloadImage()”, 5000);

Add this to the head element of any page you want to use it in. In this code, it assumes your image has an id of “randimg”. Change this if you need to, but make sure that the id of the image matches the id used in the Javascript. Also make sure that the src we are changing it to is the same as the src for your image. And don’t forget the question mark, it’s important! (We’re using a trick that fools your browser into thinking the image hasn’t already been cached, by adding a dummy parameter, the current time, to the URL.)

This example assumes you want the image to refresh every 5 seconds. Change the second parameter of setTimeout to anything you want, it’s the time to wait in milliseconds. If you don’t want to auto-refresh the image, remove both lines with setTimeout and then you can call reloadImage just like any other function. For example, you could add an onClick event to a button and have that button reload the image. Note that getTime is always needed, even if you’re not using the function as an auto-refresh! It’s needed for the cache trick, explained above.

If you’re using Plone, you won’t add this to any head element but rather through your Javascript registry at /portal_javascripts. Remember, this script will be on ALL your pages, so don’t give any images an id of “randimg” (or whatever you chose) unless you want them rotated.