JavaScript: Given a list of image URLs, how do I display the first image not shown?

I get a list of image urls, and currently I have some 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 (ie Set myImage.style.display = "inline") the first one that is not broken. It is pretty simple. However, this requires me to request all images.

What I would like to do is upload each image one at a time and determine if it has broken. If the image is broken, try downloading the following. If it’s good, display it and ignore the rest. (This will save a number of unnecessary queries.)

The algorithm is quite simple, but the trick is the image loading time. The problem is that the image may not load before the isBroken check is performed, so a good image may be ignored. Then the approach would be to handle img onload and onerror events in the solution.

I am posting here to find out if anyone has encountered a similar problem and what was their solution.

Thanks!

+3
source share
1 answer

You seem to 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 display the image, since you know that it succeeded.

You probably want to get rid of the global variable, but here is 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 } } 
+8
source

All Articles