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

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.

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.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>Refresh Image</title>
</head>
  
<body>
    <!-- Display the image -->
    <img id="gfgimage" src="bg.png" 
        height="500" width="700" />
  
    <script>
        // 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;
        console.log(image.src);
    </script>
</body>
  
</html>

chevron_right


Output:
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.

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.