Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 13 Jun, 2022
View Discussion
Improve Article
Save Article

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!