Travis2375
Travis2375

Reputation: 137

How to refresh image source only if new image is actually available?

<!--WunderGroundRadar--> 
<script type = "text/javascript">
   setInterval(function refreshRadar() {

   document.getElementById("content14").src =  "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1" 
  }, 900000);

</script>

I use the code above to refresh a weather radar .gif image on my website about every 15 minutes. This normally works great, but sometimes when the refresh takes place the image is broken from it's source and my site has a broken image icon until the next refresh takes place approx. 15 minutes later. I would like to set this up so that if the requested image is broken or not available at the time that the refresh function runs, I keep the image that is already loaded instead of replacing it with a broken image icon. I am willing to use any javascript or Jquery that might achieve this, but I am a novice programmer, so if you could break down any intricate code that would be much appreciated. Thanks!

Upvotes: 4

Views: 362

Answers (1)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

You can try something like this

<script type = "text/javascript">
   setInterval(function refreshRadar() {

      img = new Image();

      img.onload = function(){
         document.getElementById("content14").src = img.src;
      };

      img.src = "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1" 

  }, 900000);

</script>

it attempts to load source to a temporary image and only on successful load assings source to "content14"

Upvotes: 2

Related Questions