Thursday, September 18, 2025
HomeLanguagesJavascriptHow to get the new image URL after refreshing the image using...

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:

HTML




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


Output:

 

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.

HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

RELATED ARTICLES

Most Popular

Dominic
32299 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6664 POSTS0 COMMENTS
Nicole Veronica
11835 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11895 POSTS0 COMMENTS
Shaida Kate Naidoo
6779 POSTS0 COMMENTS
Ted Musemwa
7053 POSTS0 COMMENTS
Thapelo Manthata
6736 POSTS0 COMMENTS
Umr Jansen
6743 POSTS0 COMMENTS