0

Should be a simple while loop, appending an image and incrementing the count, until .error() is fired because the image doesn't exist.

The problem is the error event never fires. There are three images in the directory, but the page just loads indefinitely until the tab crashes. Calling .error() on an image in the html works, it's only when I append the image, then call error.

Code below:

jQuery(document).ready(function($) {
    var images = 'load';
    var i = 1;

    while(images == 'load') {
        $('.images').append('<img src="window_0' + i + '.jpg" />')
            .error(function() {
                images = 'finished';
            });
        i++;
    }

});

If I use while(i<4) it works perfectly, as the result of .error() doesn't matter. The thing is I need this to be variable so that the number of images loaded can be increased by just adding files to the directory without editing the code.

This used to be possible with an ajax call but doesn't work in my version of jQuery (1.7.1

James Dinsdale
  • 789
  • 8
  • 23
  • can't you get a file count using server code? That can be passed to page as a variable and work counter against it – charlietfl Nov 04 '12 at 21:00
  • You cannot solve that problem using this solution, because calling error callback is asynchronous. Your infinite loop blocks browser from handling any other callbacks so none will ever happen. Plus this approach wastes transfer and is highly unpredictable. – dreame4 Nov 04 '12 at 21:07
  • unfortunately server-side code is not an option in this instance (long story). The point is, the loop should not be infinite, because it should end when the fourth (non-existent) image is appended causing .error() to fire. – James Dinsdale Nov 04 '12 at 21:16
  • Managed to solve it in the end using native javascript from this question instead: http://stackoverflow.com/questions/11144261/javascript-how-to-load-all-images-in-a-folder – James Dinsdale Nov 04 '12 at 21:30

1 Answers1

1

You have two main problems here: first, you're not binding the error event to the img here, you're binding it to $('.images').

Second, javascript is (mostly) single-threaded. Even though the image loads may happen in the background, no javascript event processing can happen until your loop exits, which it won't do unless an event occurs, so you have a catch-22.

This does something similar by chaining load events, rather than waiting for an error event:

    var i = 1;
    var img;
    function next() {
        if (img) $('.images').append(img);
        img = document.createElement('img');
        $(img).load(next);
        img.src='window_0' + (i++) + '.jpg';
    }
    next();
CupawnTae
  • 14,192
  • 3
  • 29
  • 60