Skip to content
Related Articles

Related Articles

Improve Article

How to get the new image URL after refreshing the image using JavaScript ?

  • Difficulty Level : Easy
  • Last Updated : 29 Jun, 2020

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

Approach: To change the URL without affecting the image, you can change the parameter that can be attached to the end of the URL. The parameter needs to be unique. We can use a timestamp, the URL will always be unique.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

To refresh 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 timestamp parameter to ensure it does not access it from the cache.


<!DOCTYPE html>
    <title>Refresh Image</title>
    <!-- Display the image -->
    <img id="gfgimage" src="bg.png" 
        height="500" width="700" />
        // Create a timestamp
        var timestamp = new Date().getTime();
        // Get the image element 
        var image = document.getElementById("gfgimage");
        // Adding the timestamp parameter to image src
        image.src = "bg.png?t=" + timestamp;

Image URL before refresh

Now, even if the image is replaced with a new image it will load the new image. In general, this may have some performance issues as it won’t be using the image from the cache and will have to use the image from the server always.

My Personal Notes arrow_drop_up
Recommended Articles
Page :