user2983770
user2983770

Reputation: 3

How to check all images in array have loaded

I have an array containing a range of images and I need to check if all images have loaded and return true once all have been loaded before continuing. So far I have:

var image = new Array();
var c=0;
jQuery('.banner-images img').not('.sizer').each(function() {
    image[c] = new Image();
    image[c].src=jQuery(this).attr('src');
    c++;
});
var fc = image.length;
for(i=0;i<fc;i++) {
    // ???
}

I'm not sure where to take it from there. Any suggestions?

Upvotes: 0

Views: 306

Answers (4)

Bali Balo
Bali Balo

Reputation: 3408

There are many ways to do this.
I've done a function which load an array of images and when finished call a callback function with the array of loaded images and additional parameters that you can chose.

function load(files, callback)
{
    var args = Array.prototype.slice.call(arguments);
    var loadedFiles = [];
    var load = Function.prototype.bind.apply(callback, [callback,loadedFiles].concat(args.slice(2)));
    for(var i = files.length;i--;)
    {
        load = (function(f, i)
        {
            return function()
            {
                // console.log('Loading '+(i+1)+'.');
                var file = new Image();
                loadedFiles.push(file);
                file.onload = f;
                file.src = files[i];
            };
        })(load, i);
    }
    load();
}

// And then you use it like this
// load(['a.jpg', 'b.jpg'], function(files, extraValue1){console.log('loaded');}, 'anything')

Here is an exemple which can help you understand: http://jsfiddle.net/uN5m9/.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Hook up an onload handler to the new image to call a function to increment a counter. When the counter is the same size of the array, it's done.

Upvotes: 1

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

You need to know that when a code has stopped executing (when everything has loaded or an error came out) the function returns true, unless you set it to handle some errors.

However you can prevent the execution of others untill the image is loading by using preventDefault().

Upvotes: 0

michael truong
michael truong

Reputation: 311

There is no built-in javascript way, but here's a good way

https://github.com/desandro/imagesloaded

Upvotes: 0

Related Questions