Javascript - wait images to be loaded

前端 未结 6 803
栀梦
栀梦 2021-01-07 03:46
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\";

imm         


        
6条回答
  •  佛祖请我去吃肉
    2021-01-07 04:52

    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.

提交回复
热议问题