19

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?

ylluminate
  • 12,102
  • 17
  • 78
  • 152

5 Answers5

18
<img onerror="dosomthing()" ...>
Ashraf
  • 2,612
  • 1
  • 20
  • 35
  • 4
    That's `$('#myImg').bind('error', function(e){ ... });` in jQuery :) – jocull Jun 21 '13 at 20:16
  • The most straightforward solution for replacing images that fail to load with a default image. – MastaBaba Jul 14 '15 at 01:44
  • 3
    What should "dosomthing()" do to reload the image? – Barmar Aug 08 '18 at 15:45
  • @Barmar : It might be changing the `src` of the `img` to a default resource : Something like : `$('#img1').attr('src','images/no-profile-photo.png')` . Or as you suggested , a logical code to re attempt to load the same image . – Ashraf Aug 09 '18 at 03:23
9

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

Community
  • 1
  • 1
Ramiz Uddin
  • 4,249
  • 4
  • 40
  • 72
  • That is excellent input. Thanks! I like the additional information. Here's the original js I'm using to actually reload some images based on a class every 60 seconds. I would *very* much appreciate seeing this integrated into the following code I'm using so that these two examples you have are properly integrated (I'm quite new to working in js at any significant level): http://j.mp/wzi7FI – ylluminate Jan 23 '12 at 08:16
  • Sorry ylluminate. I got away. I have edited my post and I hope this will help you. – Ramiz Uddin Jan 23 '12 at 10:04
  • Worked out real well, thanks! Have a few tweaks to make, but you got it down well enough. Super job. – ylluminate Jan 24 '12 at 06:37
5

take a look at this code:

$('img.autoFix').error(function(){
    var src = this.src;
    this.src = src.substr(0, src.indexOf('?')) + '?t=' + new Date().getTime()
});
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Kiyan
  • 2,155
  • 15
  • 15
  • 1
    Wouldn't it get into an infinite loop in case the image does not exist or there's some other persistent issue with it? – fejese Jan 06 '15 at 10:09
  • 1
    it will, but if you want you can use data attribute to limit number of tries. – Kiyan Jan 07 '15 at 11:35
  • 2
    ... or use a setTimeout in the error function to not make it reload like crazy. – markj Jan 12 '15 at 08:45
4

After mixing together a few ideas from other answers, along with my own, I came up with something that worked for me:

Add this to your img elements:

onerror="tryAgain(this)"

Script:

<script>  
  function tryAgain(e) 
  {
    setTimeout(reloadImg, 1000, e);
  }

  function reloadImg(e)
  {
    var source = e.src;
    e.src = source;
  }
</script>

You can of course change the timeout to whatever you want. (forgive me for not using $ in my answer; I'm new to JS and haven't used JQuery at all).

Steph
  • 831
  • 6
  • 19
2

This a very simple approach that handles all images on the page.


https://github.com/doomhz/jQuery-Image-Reloader

jQuery Image Reloader

Forces the browser to retry loading the broken images. A decent solution for images stored in a cloud (i.e Amazon S3).

Why and when to use it?

This plugin is effective when you load images from a cloud (i.e. Amazon S3) and the CDN has a delay until the image is accessible. The browser will display a broken image icon instead and won't retry to reload it. jQuery Image Reloader will take care of that.

Plugin code

The only code you need to activate the plugin is this:

$(".slow-images").imageReloader();
MockWhy
  • 153
  • 3
  • 12