[jquery] How to reload/refresh an element(image) in 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.

This question is related to jquery

The answer is


Some times actually solution like -

$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));

also not refresh src properly, try out this, it worked for me ->

$("#Image").attr("src", "dummy.jpg");
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));

To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.

//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);

function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
    //get the src attribute
    source = jQuery(".xyro_refresh").attr("src");
    //remove previously added timestamps
    source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
    //prep new src attribute by adding a timestamp
    new_source = source + "?timestamp="  + new Date().getTime();
    //alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
    //set the new src attribute
    jQuery(".xyro_refresh").attr("src", new_source);
}

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 :-)


I may have to reload the image source several times. I found a solution with Lodash that works well for me:

$("#myimg").attr('src', _.split($("#myimg").attr('src'), '?', 1)[0] + '?t=' + _.now());

An existing timestamp will be truncated and replaced with a new one.


Using "#" as a delimiter might be useful

My images are kept in a "hidden" folder above "www" so that only logged users are allowed access to them. For this reason I cannot use the ordinary <img src=/somefolder/1023.jpg> but I send requests to the server like <img src=?1023> and it responds by sending back the image kept under name '1023'.

The application is used for image cropping, so after an ajax request to crop the image, it is changed as content on the server but keeps its original name. In order to see the result of the cropping, after the ajax request has been completed, the first image is removed from the DOM and a new image is inserted with the same name <img src=?1023>.

To avoid cashing I add to the request the "time" tag prepended with "#" so it becomes like <img src=?1023#1467294764124>. The server automatically filters out the hash part of the request and responds correctly by sending back my image kept as '1023'. Thus I always get the last version of the image without much server-side decoding.


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.


Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.

function imageUploadComplete () {
    $("#image_container").html("<img src='" + newImageUrl + "'>");
}

Based on @kasper Taeymans' answer.

If u simply need reload image (not replace it's src with smth new), try:

_x000D_
_x000D_
$(function() {_x000D_
  var img = $('#img');_x000D_
_x000D_
  var refreshImg = function(img) {_x000D_
    // the core of answer is 2 lines below_x000D_
    var dummy = '?dummy=';_x000D_
    img.attr('src', img.attr('src').split(dummy)[0] + dummy + (new Date()).getTime());_x000D_
_x000D_
    // remove call on production_x000D_
    updateImgVisualizer();_x000D_
  };_x000D_
_x000D_
_x000D_
  // for display current img url in input_x000D_
  // for sandbox only!_x000D_
  var updateImgVisualizer = function() {_x000D_
    $('#img-url').val(img.attr('src'));_x000D_
  };_x000D_
_x000D_
  // bind img reload on btn click_x000D_
  $('.img-reloader').click(function() {_x000D_
    refreshImg(img);_x000D_
  });_x000D_
_x000D_
  // remove call on production_x000D_
  updateImgVisualizer();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<img id="img" src="http://dummyimage.com/628x150/">_x000D_
_x000D_
_x000D_
<p>_x000D_
  <label>_x000D_
    Current url of img:_x000D_
    <input id="img-url" type="text" readonly style="width:500px">_x000D_
  </label>_x000D_
</p>_x000D_
_x000D_
<p>_x000D_
  <button class="img-reloader">Refresh</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_


with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:

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

I simply do this in html:

<script>
    $(document).load(function () {
        d = new Date();
        $('#<%= imgpreview.ClientID %>').attr('src','');
    });
</script>

And reload the image in code behind like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        image.Src = "/image.jpg"; //url caming from database
    }

}


This works great! however if you reload the src multiple times, the timestamp gets concatenated to the url too. I've modified the accepted answer to deal with that.

$('#image_reload_button').on('click', function () {
    var img = $('#your_image_selector');
    var src = img.attr('src');
    var i = src.indexOf('?dummy=');
    src = i != -1 ? src.substring(0, i) : src;

    var d = new Date();
    img.attr('src', src + '?dummy=' + d.getTime());
});