How to determine loading status of images not attached to the DOM
- by Rookwood
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.