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

jquery

Is it possible to reload an image with an identical file name from a server using jQuery?

For example, I have an image on a page, however, the physical image can change based on user actions. Note, this does not mean the file name changes, but the actual file itself.

ie:

  • User views image on default page
  • User uploads new image
  • Default image on page does not change(I assume this is due to the file name being identical, the browser uses the cached version)

Regardless of how often the code below is called, the same issue persists.

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

In the jQuery documentation, the "load" function would be perfect if it had a default method of firing the event as opposed to binding a callback function to a successful/complete load of an element.

Any assistance is greatly appreciated.

Best Answer

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());