Jason Mayo
Jason Mayo

Reputation: 356

Preloading Images & [object HTMLImageElement]

I'm trying to create preloader, but when I run this, console displays this:

Loaded [object HTMLImageElement] of 5

from this line of code

console.log('Loaded ' + images[i] + ' of ' + images.length);

But Ideally I want it to display:

"Loaded 1 of 5"

How can I fix this? I just want to create this as a callback so I know when all images in a certain panel has loaded.

$(panel).each(function(){

    // Find Panel
        var panelId = $(this).attr('id');
        console.log('Loading ' + panelId);  

    // Find Images
        var images = $(this).find('img');
        var path = images.attr('src');
        console.log('Total of ' + images.length + ' Images');

    // Preload Images
        for( i= 0; i < images.length; i++ ) {

            images[i] = new Image();
            images[i].src = path;
            images[i].onload = function(){
                console.log('Loaded ' + images[i] + ' of ' + images.length);
            };

        }

    // End

});

Also - How could I modify my each() loop, to check each a panel, after the previous panel has finished checking?

Any help would be great. Thanks.

Upvotes: 2

Views: 1950

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075815

Just declare a counter and increment it as you go:

$(panel).each(function(){
        var loaded = 0; // <== The counter

    // Find Panel
        var panelId = $(this).attr('id');
        console.log('Loading ' + panelId);  

    // Find Images
        var images = $(this).find('img');
        var path = images.attr('src');
        console.log('Total of ' + images.length + ' Images');

    // Preload Images
        for( i= 0; i < images.length; i++ ) {

            images[i] = new Image();
            images[i].src = path;
            images[i].onload = function(){
                ++loaded;
                console.log('Loaded ' + loaded + ' of ' + images.length);
            };

        }

    // End

});

Don't use i, as at least one commenter suggested (and as I suggested before reading your code more carefully). i will always be images.length by the time the load callback is done.

Another change you need to make is to set the onload callback before setting src, so instead of:

// PROBLEM, sets up a race condition
images[i].src = path;
images[i].onload = function(){
    // ...
};

do this:

images[i].onload = function(){
    // ...
};
images[i].src = path;

JavaScript on web browsers is single-threaded (barring the use of web workers), but the web browser is not. It can easily check its cache and see that it has the image and run its code to trigger the load handlers between the line setting src and the line setting onload. It will queue up the handlers to be run the next time the JavaScript engine is available, but if your handler isn't there to get queued, it won't get queued, and you never get the load event callback.

Upvotes: 4

Related Questions