Javascript - wait images to be loaded
image, javascript
Solution
No need for loops. You could let them call a function that checks if l and l2 are true and perform the thing you want to do:
var onLoaded = function() {
if (l && l2) {
// do your stuff
}
}
imm.onload = function(){
l = true;
onLoaded(); // call to onLoaded
}
imm2.onload = function(){
l2 = true;
onLoaded(); // call to onLoaded
}
It is basically a simpler form of the Observer Pattern. There are jQuery plugins such as Radio.js that encapsulate this for you.
Problem
``` var l = false; var l2 = false; var imm = new Image(); imm.src = "b.png"; imm.onload = function(){ l = true; } var imm2 = new Image(); imm2.src = "c.png"; imm2.onload = function(){ l2 = true; } ``` How can I tell this javascript to start a function only if `l` and `l2` are true? Should I set a loop which constantly check for these two variables? Is there any more efficient way? I don't want my script to start without images but with `.onload` I can wait for just one image to be loaded and not all of them. Thanks for your help!