I\'m trying to create preloader, but when I run this, console displays this:
Loaded [object HTMLImageElement] of 5
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.