Updating images with Javascript

This is a quicktip on how to update images on a webpage that retain the same filename but is periodically updated, without having to perform a full page load.

The solution is quite obvious. It’s as simple as updating the src attribute of the image. The tricky part is to get the browser to actually display the new image and not just a cached copy of it. To do this we must trick the browser into thinking it’s a new file that it haven’t displayed before. This is preferably done by inserting a unique filename to the src attribute. There’s a couple a way of doing this but in this example it’s done by adding the time in milliseconds (ms) as a querystring at the end of the filename.

function updateImage(src) {
    if(src.indexOf('?') > -1) {
        src = src.substr(0, src.indexOf('?'));
    }
    return src + '?' + (new Date()).getTime();
}
var img = document.getElementById('myImage');
img.src = updateImage(img.src);

You could theoretically add a hash (#) after the filename instead of a querystring (?), but unfortunately that doesn’t work in Internet Explorer. So stick with the querystring and you will be fine.

About the author

Gabriel Svennerberg is an independent Interaction/UI Designer and Web Developer living in Sweden. When he's not busy building web application designed for humans, he writes about all things web on his site In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress.
  • http://www.heavyworks.net Jan Seidl

    Just watch out to bogus access data when using access log traffic analyzers like Awstats.

    PS: A typo: cashed -> cached — I know you wanna cash, I want it too!

  • http://www.svennerberg.com Gabriel Svennerberg

    Thanks Jan, and yeah, I want lots of cash!! :-)

  • http://www.webdersanesi.com ahmet

    so useful approach, thanx gabriel..