views:

343

answers:

1

I receive a list of image URLs and currently I have several hidden img elements on my page (one for each URL in the list). When the page has finished loading, I use JavaScript to check the images and display (i.e., set myImage.style.display="inline") the first one that is not broken. This is quite simple. However, it requires that I request all images.

What I would like to do is to load each image one at a time and determine whether it is broken. If an image is broken, try loading the next one. If it's good, display it and ignore the rest. (This will save a number of unecessary requests.)

The algorithm is easy enough, but the trick is the image loading time. The problem is that the image may not have loaded before the isBroken check occurs, thus a good image could be ignored. The approach then would be to work the img's onload and onerror events into the solution.

I am posting here to see whether anyone has faced a similar problem and what their solution might have been.

Thanks!

+7  A: 

It seems like you have the right idea. I would write a function that tries to load the first URL and set the onerror property to call the function again. You can set the onload function to actually show the image, since you know it succeeded.

You would probably want to get rid of the global variable, but here's the idea:

var images = ["bad.jpg", "error.jpg", "good.jpg", "not-tried.jpg"];

function tryNextImage() {
    var url = images.shift();
    if (url) {
        var img = new Image();

        img.onload = function() {
            document.body.appendChild(img);
        };
        img.onerror = tryNextImage;

        img.src = url;
    }
    else {
        // Handle the case where none of the images loaded
    }
}
Matthew Crumley