Javascript - wait images to be loaded

前端 未结 6 754
栀梦
栀梦 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:45

    If you want to load images in order, from a given list of URLs, then I find this to be useful:

    preloadImages_helper("firstURL", "secondURL");
    
        function preloadImages_helper(){
            var args =  Array.prototype.slice.call(arguments);
            if(!(args === undefined) && args.length > 0){
                var img = new Image();
                img.src = arguments[0];
                img.onload = function(){
                    preloadedImages.push(img);
                    console.log("pushing image");
                    //Don't forget to call user code!
                    if(!(args === undefined) && args.length > 1){
                        args.shift();
                        preloadImages_helper.apply(this, args);
                    }
                    else{
                        console.log("finished loading images");
                        userCode();
                    }
                };
            }
        }
    

提交回复
热议问题