1

I've a series of folders containing images numbered sequentially (1.jpg, 2.jpg, 3.jpg… etc). I'm trying to load the images with a for loop until the first non existing image is found. I read some other article managing similar problem (check if an image exists) with onload and onerror callback functions, but I'm stuck. Here there is some code I wrote to store the images in an array and display them in the HTML page along with their src:

var arrImages = new Array();

function loadImgSeq() {
    for (var i = 0; i < 11; i++) {
        arrImages[i] = new Image();
        arrImages[i].src = "slides/" + i + ".jpg"
        arrImages[i].width = 400;
        document.body.appendChild(arrImages[i]);
        document.write("<p>"+arrImages[i].src+"</p>");
    }
}

PS:I've no experience in computer programming, I just do it as hobbyist.

2 Answers2

0
  1. do not document.write after load
  2. do not mix append with document.write

Here is a way

var i=0,img;
function loadImgSeq() {
  i++; 
  var img = new Image();
  img.onload=function() {
    document.body.appendChild(img);
    loadImgSeg(); // if success, do it again - will not be called if error
  }
  img.src = "slides/" + i + ".jpg";// IMPORTANT, must be AFTER onload/onerror handler
}

UPDATE: If you get IE issues from cache, try

img.onload=img.complete=function() {
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • don't forget to check for `img.ready` as well, since IE doesn't always trigger the `onload` event when pulling something from cache. – Jeremy J Starcher Dec 24 '13 at 21:34
  • Really? I have not seen that. I would need to check that. Thanks – mplungjan Dec 25 '13 at 06:46
  • Ooops... I'm bad. It isn't `img.ready` -- it is `img.complete.` From checking other SO answer, it seems to only affect IE8 and below. Was on my mind since we support IE8 at work. (The onload event doen't fire if the the image is loaded from cache, so one has to check img.complete then manually call the callback function.) http://stackoverflow.com/questions/1038327/image-onload-not-firing-twice-in-ie7 – Jeremy J Starcher Dec 25 '13 at 14:30
0

Here's one:

var found = true;
while(found)
{
    var img = new Image();
    img.src = 'path';
    found = img.naturalWidth?  true : false;
}
Frank Conry
  • 2,694
  • 3
  • 29
  • 35