Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS/JQuery Retry Img Load After 1 Second

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);
}
like image 617
Chris Avatar asked Oct 30 '13 03:10

Chris


1 Answers

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.)

like image 141
Paul Draper Avatar answered Sep 29 '22 20:09

Paul Draper