In usability we trust

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.

Share this article

  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Digg
  • StumbleUpon
  • Google Bookmarks
  • Mixx
  • Print

Comments

RSS feed for comments on this post

1. April 1st, 2009 at 7.47 by 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!

2. April 1st, 2009 at 9.31 by Gabriel Svennerberg | Author comment

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

3. May 15th, 2009 at 2.07 by ahmet

so useful approach, thanx gabriel..

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>