I have a code that depends on an array of large images being loaded first, so I’m trying to do something like this:
var loading = 0;
var i = 0;
var imgs = [];
var background = [
'bg1-1', 'bg1-2', 'bg1-3', 'bg1-4',
'bg2-1', 'bg2-2', 'bg2-3', 'bg2-4',
'bg3-1', 'bg3-2', 'bg3-3', 'bg3-4',
'bg4-1', 'bg4-2', 'bg4-3', 'bg4-4'
];
for (i = 0; i < background.length; i++) {
imgs[i] = document.getElementById(background[i]);
imgs[i].onload = function() {
loading++;
}
}
while (loading < 16) { }
alert('images loaded!'); //I need to ensure images are fully loaded here.
So, it just hangs and never pulls out of the while loop.
Put the condition and the alert in the callback.
And really it would be better to reuse that function.