How to determine loading status of images not attached to the DOM
Posted
by Rookwood
on Stack Overflow
See other posts from Stack Overflow
or by Rookwood
Published on 2010-06-03T15:32:35Z
Indexed on
2010/06/03
15:34 UTC
Read the original article
Hit count: 233
I am working on a bit of javascript to plot data on a <canvas
>. The data points are marked by one of several different (small) image files. I am attempting to have the plot method wait until all the images are loaded. My best attempt thus far is such:
var icon = {
left : {
air : new Image(),
bone : new Image(),
},
right : {
air: new Image(),
bone : new Image(),
},
};
icon.left.air.src = option.imgPath + 'left.air.png';
icon.right.air.src = option.imgPath + 'right.air.png';
icon.left.bone.src = option.imgPath + 'left.bone.png';
icon.right.bone.src = option.imgPath + 'right.bone.png';
function main() {
Canvas.draw();
// Make sure our image icons are loaded before we try to plot
$(icon.left.air).load(function() {
$(icon.right.air).load(function() {
$(icon.left.bone).load(function() {
$(icon.right.bone).load(function() {
Data.plot();
});
});
});
});
}
This works as expected most of the time. On occasion, it will fail and no data will be plotted. Inserting several console.log() statements shows that the script will silently stop working through the series of .load() statements, though code that comes after will be executed.
My questions are as follows: Am I approaching this the right way? Is there a way to attach an event to my icon object that will fire once all of the images inside are loaded?
This is a jquery plugin, so obviously jquery-based solutions are just as acceptable as vanilla javascript.
© Stack Overflow or respective owner