-1

I'm trying to call a function after all images in predefined array are loaded.

Trying smth like this

for (var i = 0; i < length; i++) {
           d = $.Deferred();
           promises.push(p);

           img = new Image();

           img.onload = function(){
               p.resolve
           }
           img.src = srcs[i];
       }

$.when.apply($, promises).done(function(){
           defImages.resolve();
       })

It does not work. What am I doing wrong?

Kotanet
  • 573
  • 1
  • 8
  • 26
  • 1
    If this is the complete code than there should be an error message in the console because `p !== d` – Andreas May 08 '18 at 15:57
  • there is p.resolve in the code. I've tried multiple variants and neither work – Kotanet May 08 '18 at 16:02
  • There's a lot of variables here that you need to provide context to: `p`, `defImages`, `promises`, `length`, `srcs`... – chazsolo May 08 '18 at 16:07
  • `resolve()` off a promise/deferred is a method. `variable.resolve` would just return reference the function, not execute it, without the parentheses. – Taplar May 08 '18 at 16:08

1 Answers1

0

   //count of all page images
var img_count=$('img').length;
   //images loaded
var img_loaded=0;

$('img').load(function(){
 img_loaded++;
 if(img_loaded==img_count){
  console.log('all images loaded');
 }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


   <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/CC-Zero-badge.svg/100px-CC-Zero-badge.svg.png">
   <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/16/CC-BY_icon.svg/100px-CC-BY_icon.svg.png">
   <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/CC-BY-SA_icon.svg/100px-CC-BY-SA_icon.svg.png">
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17