Preloading images and [HTMLImageElement object]
I'm trying to create a preloader, but when I run this, the console displays this:
Loaded [HTMLImageElement Object] of 5
from this line of code
console.log('Loaded ' + images[i] + ' of ' + images.length);
But ideally I want it to be displayed:
"Downloaded 1 of 5"
How can I fix this? I just want to create this as a callback so I know when all the images in a specific panel are 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
});
See also - How do I change the loop each()
to check each panel after the previous panel has finished checking?
Any help would be great. Thank.
source to share
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 carefully). i
will always be images.length
by the time the load callback completes.
Another change you need to make is to set the onload
callback parameter to src
, so instead of:
// PROBLEM, sets up a race condition
images[i].src = path;
images[i].onload = function(){
// ...
};
do the following:
images[i].onload = function(){
// ...
};
images[i].src = path;
JavaScript in web browsers is single threaded (prohibiting the use of web workers), but web browser is not. He can easily check his cache and make sure he has an image and run his code to run handlers load
between line src
setting and line setting onload
. It will queue up the handlers to be fired the next time the JavaScript engine runs, but if your handler is not queued it will not queue and you will never get an event callback load
.
source to share