How to reload/refresh an element(image) in jQuery

It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());

It's probably not the best way, but I've solved this problem in the past by simply appending a timestamp to the image URL using JavaScript:

$("#myimg").attr("src", "/myimg.jpg?timestamp=" + new Date().getTime());

Next time it loads, the timestamp is set to the current time and the URL is different, so the browser does a GET for the image instead of using the cached version.


This could be one of the two problems you mention yourself.

  1. The server is caching the image
  2. The jQuery does not fire or at least doesn't update the attribute

To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:

$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");

Even if this works, post some code since this is not optimal, imo :-)

Tags:

Jquery