Force an image to reload and refresh using Javascript

Force an image to reload and refresh using Javascript

Learn how to reload an image that has been cached by the browser without refreshing the page using Javascript.


Displaying an individual image that is subject to frequent change in your HTML document while only making use of the <img> element can be a bit of a challenge, mainly because modern browsers and servers are designed to optimize data usage as much as possible and make use of caching to ensure you don't have to load the same image multiple times.


Caching may be beneficial in the long run but it does make operations such as reloading an image a bit more difficult as you can't simply replace the image or reset it's source. Given that the URL of the image you are trying to load remains exactly the same before and after it was modified, the browser will assume that it is the exact same image and rather than requesting it again from the server, it will fetch it from the cache and it will not refresh.


Forcing an image reload by tricking the browser cache


The browser cache relies on the URL to determine whether content is the same or not and whether to use the stored version. This means that if we change something within the URL and then attempt to reload the image, the cache will no longer be able to determine that it is the same resource and will rather fetch it again from the server.


To modify the URL without affecting the image, we can simply use a dummy query string that can be attached to the end of the URL, it just needs to be unique. For this we can just use a timestamp so that no matter when it is called, the URL will always be unique.


To reload the image in Javascript, we can simply select the <img> element and modify its src attribute to be that of the target image, along with the bogus query string to ensure it does not use the cache.


As an example, let's assume you have an image "test.jpg" which needs to be reloaded.


HTML


<img id="testimg" src="test.png">


Javascript


// create a new timestamp     
var timestamp = new Date().getTime();     
     
var el = document.getElementById("testimg");     
     
el.src = "test.png?t=" + timestamp;     
     


This code appends the timestamp to the source URL and will ensure the image is reloaded and refreshed with your new modified image. You can use this same piece of code to refresh the image as many times as you like so putting it in a function is useful.


function refreshImage(imgElement, imgURL){    
    // create a new timestamp 
    var timestamp = new Date().getTime();  
  
    var el = document.getElementById(imgElement);  
  
    var queryString = "?t=" + timestamp;    
   
    el.src = imgURL + queryString;    
}    


If you found this tutorial useful or have any questions feel free to leave a comment below!



Christopher Thornton@Instructobit 2 years ago
or