ylluminate ylluminate - 7 months ago 7
Javascript Question

How to detect image load failure and if fail, attempt reload until success?

I have some images loading from offsite and have no control over their availability. I've found that under heavy load they are sometimes failing to load, but on a quick refresh they'll show right up.

Is there a way to detect if images fail to load and then if so, evoke a reload on the img src until it loads? If so, could you please provide an example?

Answer

Here something I compiled which might help. I couldn't manage to do testing of this please let me know if you are having any issues.

$(function() {
   var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');

  // Now, no such image with
   // a spinner
   if($images.length === 0 && window.imageLocator)
     clearInterval(window.imageLocator);


    window.imageLocator = setInterval(function() {
        $images.each(function() {
            $this = $(this);
            if (!$this.data('src')) {
                $this.data('src', $this.prop('src'));
            }

            $this.prop('src', $this.data('src') + '?timestamp=' + new Date().getTime());
            console.log($this.prop('src'));
        });
    }, 60 * 1000);

   // suppose, an error occured during
   // locating the src (source) of the
   // image - image not found, network
   // unable to locate the resource etc.
   // it will fall in each time on error
   // occurred 
   $('img.imageClassUpdateAtInterval').error(
          function () {   
                 // set a broken image
                 $(this).unbind("error").attr("src", "/assets/broken.gif"); 
                 // setting this up in relative
                 // position
                 $(this).css("position", "relative");
                 $(this).apppend("<span>Error occured</span>");
                 $(this).find("span").css({"position": "absolute", "background-color": "#252525", "padding": ".3em", "bottom": "0"});
   });

});

The above solution is compiled from two different solutions commenced by @user113716 and @travis