最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - wait images to be loaded - Stack Overflow

programmeradmin3浏览0评论
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!

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!

Share Improve this question asked Apr 11, 2012 at 10:39 SaturnixSaturnix 10.6k18 gold badges68 silver badges125 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 11

More elegant way in my opinion:

var loadedImagesCount = 0;
var imageNames = ["b.png", "c.png"];
var imagesArray = [];
for (var i = 0; i < imageNames.length; i++) {
    var image = new Image();
    image.src = imageNames[i];
    image.onload = function(){
        loadedImagesCount++;
        if (loadedImagesCount >= imageNames.length) {
            //loaded all pictures
        }
    }
    imagesArray.push(image);
}

Instead of messing with lots of different image variables, just store the image names in plain array then loop over this and count how many pictures are loaded.

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.

Here is a generic one (works with any number images)

function preload( images, callback){
   var imageElements = [],
       counter = images.length,
       lfunc = function(){if (--counter === 0 && callback) callback(imageElements);};

   // first create the images and apply the onload method
   for (var i = 0, len = images.length; i < len; i++){
      var img = new Image();
      imageElements.push( img );
      img.onload = lfunc;
      img.src = images[i];
   }
}

function codeOncePreloadCompletes(preloadedImages){
  // Do whatever you want here
  // images are preloaded
  // you have access to the preloaded image if you need them
  // with the preloadedImages argument
}

// USAGE

preload( ['b.png', 'c.png'], codeOncePreloadCompletes);

// OR

preload( ['b.png', 'c.png'], function(preloadImages){
   // write directly here what to do after preload
});

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();
                }
            };
        }
    }

If these are the only 2 times throughout your entire script that l and l2 are set, then you can check after setting the values.

var l = false;
var l2 = false;

var imm = new Image();
imm.src = "b.png";

imm.onload = function(){
  l = true;
  if (l && l2) {
    myFunc();
  }
}

var imm2 = new Image();
imm2.src = "c.png";

imm2.onload = function(){
  l2 = true;
  if (l && l2) {
    myFunc();
  }
}

function myFunc(){
  //do stuff
}

you don't have to constantly check, just check the other each time one finishes, that way, when the second is done your function will fire, and you will only have had to "check" once. var l = false; var l2 = false;

var imm = new Image();
imm.src = "b.png";

imm.onload = function(){
l = true;

if (l2)
   call yourFunction();

}

var imm2 = new Image();
imm2.src = "c.png";

imm2.onload = function(){
l2 = true;

if (l)
   call yourFunction();
}
发布评论

评论列表(0)

  1. 暂无评论