8

I have a request calling up a bunch of images like so:

<a href='www.domain1.com'><img src='../image/img1.png' onerror='imgError(this);'/></a>
<a href='www.domain2.com'><img src='../image/img2.png' onerror='imgError(this);'/></a>

The problem is when the call is made some of the images (~20%) are not ready yet. They need another second.

So in js or jquery what I would like to do is on error get the images that failed, wait 1 second, then try to load those failed images again. If they fail on the 2nd try -- oh well, Im okay with that. But Im not doing this correctly... Should I not be calling a timeout inside of another method in js?

function imgError(image) {
    image.onerror = "";
    image.src = image;

    setTimeout(function () {
        return true;
    }, 1000);
}
Samuel O'Malley
  • 3,471
  • 1
  • 23
  • 41
Chris
  • 18,075
  • 15
  • 59
  • 77
  • Why in the world do you want to do this? Besides the issues in your implementation, I suspect that setting `img.src` to what it's already set doesn't do anything. – jfriend00 Oct 30 '13 at 03:26
  • Haha. Well. Im actually using imagemajick in between the initial ajax and loading the images. What is the better practice for something like this? Thank u btw 4 the comment... – Chris Oct 30 '13 at 03:28
  • 1
    Check out this answer here: http://stackoverflow.com/questions/4285042/can-jquery-ajax-load-image – Samuel O'Malley Oct 30 '13 at 03:28
  • FYI, @SamuelO'Malley, though the OP mentions AJAX, I believe there is no AJAX here, or needing to be here. – Paul Draper Oct 30 '13 at 04:31
  • Thanks @PaulDraper, I wasn't sure if he actually wanted to use AJAX or not. – Samuel O'Malley Oct 30 '13 at 04:50
  • My apologies for lack of clarity. Thank you both for your help and edits. – Chris Oct 30 '13 at 04:57

1 Answers1

12

Add a cache breaker.

function imgError(image) {
    image.onerror = null;
    setTimeout(function (){
        image.src += '?' + +new Date;
     }, 1000);
}

(This assumes your image URL doesn't already have a query string, per the example. If it does, a little more work is obviously required.)

Paul Draper
  • 78,542
  • 46
  • 206
  • 285