Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 13 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials