Checking For Multiple Images Loaded


Answer :

If you want to call a function when all the images are loaded, You can try following, it worked for me

var imageCount = images.length; var imagesLoaded = 0;  for(var i=0; i<imageCount; i++){     images[i].onload = function(){         imagesLoaded++;         if(imagesLoaded == imageCount){             allLoaded();         }     } }  function allLoaded(){     drawImages(); } 

Can't you simply use a loop and assign the same function to all onloads?

var myImages = ["green.png", "blue.png"];  (function() {   var imageCount = myImages.length;   var loadedCount = 0, errorCount = 0;    var checkAllLoaded = function() {     if (loadedCount + errorCount == imageCount ) {        // do what you need to do.     }   };    var onload = function() {     loadedCount++;     checkAllLoaded();   }, onerror = function() {     errorCount++;     checkAllLoaded();   };       for (var i = 0; i < imageCount; i++) {     var img = new Image();     img.onload = onload;      img.onerror = onerror;     img.src = myImages[i];   } })(); 

Use the window.onload which fires when all images/frames and external resources are loaded:

window.onload = function(){   // your code here........ }; 

So, you can safely put your image-related code in window.onload because by the time all images have already loaded.

More information here.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer