Home > database >  How to properly refresh a page to display an image
How to properly refresh a page to display an image

Time:04-07

this should be very easy but I have been fighting for a week without any success and therefore I'm asking for your kind help. What I want to achieve is very simple.

  • I have a very simple, pure HTML, page (code below) that is to show two images.

  • The images are uploaded to the same directory via FTP

  • The page refreshes itself every 10 seconds, such that if the images have changed during the interval they should be updated in the view accordingly

Everything works as expected when I run it on my computer but it doesn't when I run it from the server. I can see the browser is indeed refreshing the page but the images do not change even though they were updated on the folder. Moreover, if I close the browser and open the page again then the new images are properly shown.

What am I missing? Many thanks in advance for your help

<!DOCTYPE HTML>
<html>
   <head>
      <title>RePlay</title>
      <meta http-equiv="refresh" content="10">
   </head>
   <body id = "body" style = "text-align:center;">
      <h1 style = "color:green;" >
         RePlay
      </h1>
      <h2 style = "color:black;" >
      Courts Live Update
      </h1>
      <img src="Image1.png" align = "left" width="500" height="333">
      <img src="Image2.png" align = "right" width="500" height="333">
   </body>
</html>

CodePudding user response:

I think this could be a cache issue. Even though the images are different after refresh, the browser is showing the previously cached images since the file name is the same. Perhaps try adding a query parameter to the end of the image src to bypass the browsers caching functionality for images with the same src. Try writing it like this and see if it works:

<!DOCTYPE HTML>
<html>

<head>
   <title>RePlay</title>   
   <meta http-equiv="refresh" content="10">
</head>

<body id = "body" style = "text-align:center;">
   
   <h1 style = "color:green;" >
       RePlay
   </h1>

   <h2 style = "color:black;" >
       Courts Live Update
   </h1>
   

   <img id="img-1" src="Image1.png" align = "left" width="500" height="333">
   <img id="img-2" src="Image2.png" align = "right" width="500" height="333">

</body>
<script>
 let img1 = document.getElementById('img-1');
 let img2 = document.getElementById('img-2');

 img1.src = 'Image1.png?t='   new Date().getTime();
 img2.src = 'Image2.png?t='   new Date().getTime();
</script>
</html>

In this example, I'm adding the datetime to a query parameter to ensure a new pathname for the image each refresh. That way the browser won't try to cache the image since the src will be different each time.

  • Related