jQuery : How to force browser to reload the images

Whenever you visit any website, the browser caches the images and other elements of the webpage which is stored at your machine. The advantage of caching is that when you next time access the webpage, If the browser has already found the resource to the URL specified then it will not make a new request unless the URL does not change. Thus this loads the page faster.

For your information, the src attribute of the image is nothing but just a GET request URL. So browser caches all the images along with their specified URLs and it will not make request to the server if the URL of the image is same.

So if you want to force the browser to reload the image every time, then you need to change the src attribute value. All you need to do is to append a random number at the end of URL so that browser always gets the images from the server.

Below jQuery code does the same thing. It takes the existing URL and then appends a random number and assign back the URL to src attribute.

?$(document).ready(function(){
  $('img').attr('src', $('img').attr('src') + '?' + Math.random());
});?

Note: Caching is a great feature and you should not be doing (forcing browser to reload) this unless it is necessary as it saves your servers bandwidth and also loads the webpage faster.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...