In usability we trust

UX and all things web

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.


  1. 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!

  2. Thanks Jan, and yeah, I want lots of cash!! 🙂

  3. so useful approach, thanx gabriel..

Leave a Reply

Your email address will not be published.