Cathal Coffey
Cathal Coffey

Reputation: 1117

Keep trying to reload image until successful but don't show intermediate broken image icon

I have the following mechanism in place which keeps trying to load an image with a delay between retries for a maximum of 10 attempts.

<img onerror ="imgError(this);" />

<script type='text/javascript'>
  function imgError(image) {
    if (!image.hasOwnProperty('retryCount')){
      image.retryCount = 0;
    }

    if (image.retryCount < 10){
      setTimeout(function (){
          image.src += '?' + +new Date;
          image.retryCount += 1;
      }, 1000);
    }
  }
</script>

This works great, the only problem is that the first time the image fails to load an error icon is displayed. This is really ugly as you can see in the following screenshot.

enter image description here

A few seconds later, when the image pops into existence (generated as a thumbnail from a larger image using AWS lambda), it is loaded and displayed successfully.

My question is how can I avoid the ugly intermediate broken image icon from displaying? I would prefer for either nothing to display or some text saying "generating thumbnail...".

Upvotes: 4

Views: 5806

Answers (2)

Arnauld
Arnauld

Reputation: 6130

You may want to put a temporary placeholder image as the original source, attempt to load the actual image in the background and inject it if/when it becomes available.

The following code also includes a global timeout so that server and network delays are taken into account.

<html>
<script type='text/javascript'>
  function loadImage(id, src) {
    var ts = Date.now(), img = new Image;

    img.onerror = function() {
      if(Date.now() - ts < 10000) {
        setTimeout(function() { img.src = src; }, 1000);
      }
    }
    img.onload = function() {
      document.getElementById(id).src = src;
    }
    img.src = src;
  }
</script>

<img id="myImage" src="placeholder.png" />
<script>loadImage("myImage", "whatever.png");</script>
</html>

But you still get a 404 error that is displayed in the console for each failed attempt. So, you really should consider a server side fix if possible -- as already suggested.

Upvotes: 1

Suhail Keyjani
Suhail Keyjani

Reputation: 488

you can use opacity in style like this

function showme(elem)
{
$(elem).css("opacity",1)
}
function imgError(image) {
    if (!image.hasOwnProperty('retryCount')){
      image.retryCount = 0;
    }

    if (image.retryCount < 10){
      setTimeout(function (){
          image.src += '?' + +new Date;
          image.retryCount += 1;
      }, 1000);
    }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img style="opacity:0" onload="showme(this)" onerror ="imgError(this);" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRIqW6zLho0lKtLBP3J5izulhQhTsKyl2L-a1LC9vtidlQRK3ogQQ" />

Upvotes: 0

Related Questions