Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is image onload not working

Tags:

javascript

I realize this is a common question asked by novice javascript programmers which I am. Console.log(img) and console.log("before onload") execute correctly but I never see an Image Loaded message.

AssetManager.loadImages = function(urls) {
   var images = [];
   var urlCount = urls.length;
   for (var i=0; i<urlCount; i++) {
      var img = new Image();
      images.push(img);
   }
   var urlsLoaded = 0;
   for (var i=0; i<urlCount; i++) {
      (function(img) {
         console.log(img);
         console.log("before onload");
         img.onload = function(e) {
            console.log("Image Loaded!");
            urlsLoaded++;
            if (urlsLoaded >= urlCount) {
               AssetManager.callback(images);
            }
         }
      })(images[i]);            
      images[i].src = urls[i];
   }
}
like image 745
user2267395 Avatar asked Dec 06 '22 07:12

user2267395


2 Answers

For anyone who made the same mistake as me - make sure onload is all lowercase and not camel case: onLoad.

This good:

img.onload = function () { };

This bad:

img.onLoad = function () { };
like image 135
kenecaswell Avatar answered Dec 23 '22 13:12

kenecaswell


Try var img = document.createElement("img");

or

AssetManager.loadImages = function(urls) {
    var images = new Array();
    var urlCount = urls.length;
    var urlsLoaded = 0;
    var leImg;
    for (var i=0; i<urlCount; i++) {
        leImg = document.createElement("img");
        leImg.onload = function(e){
            urlsLoaded++;
            if (urlsLoaded >= urlCount) {
               // AssetManager.callback(images); --> this is balls, still
            }
        }
        leImg.src = urls[i];
        _images.push(leImg);
    }

}

(not tested, and drunk)

like image 23
Miguel Alejandro Fuentes Lopez Avatar answered Dec 23 '22 13:12

Miguel Alejandro Fuentes Lopez