Aariba
Aariba

Reputation: 1194

Execute js after all image loaded

(I searched, but not find exactly/easy solution)
I'm trying to execute JS after all images completely loaded. My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div.

HTML:

<div class='main-slider my-loader'>
<img src="/nice-girl.jpg">
<img src="/nice-car.jpg">
<img src="/nice-boy.jpg">
</div>

Execute below js when all images completely loaded

$(".main-slider").removeClass("my-loader").addClass("visible"); 


Tried :
But not work, problem is it execute before complete image load:

var imagesPre = new Array;
var success = new Array;

$('.big-slides img').each(function(){
  imagesPre.push(this.src);
});

for (i = 0; i < imagesPre.length; i++) {
    (function(path, success) {
        image = new Image();
        image.onload = function() {
          success.resolve();
        };
        image.src = path;
    })(imagesPre[i], success[i] = $.Deferred());
}

$.when.apply($, success).done(function() {
$(".main-slider").removeClass("my-loader").addClass("visible"); 
}); 


Any ideia for simple solution?

Upvotes: 0

Views: 1410

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19133

You can use load() to check if the images are loaded!

$('.imgTag').each(function(){
  $(this).load(function(){
   $(".main-slider").removeClass("my-loader").addClass("visible"); 
  })
})

This may not work sometimes when the images are cached by the browser. Please check Caveats of the load event when used with images

var img = $('img')
var count = 0
img.each(function(){
  $(this).load(function(){
    count = count + 1
    if(count === img.length) {
      $('.main-slider').removeClass('my-loader').addClass('visible')
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main-slider my-loader'>
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
</div>

But, this answer is a working case.

Upvotes: 1

Moslem_mh
Moslem_mh

Reputation: 189

<div class='main-slider my-loader'>
<img class="imgTag" src="/nice-girl.jpg">
<img class="imgTag" src="/nice-car.jpg">
<img class="imgTag" src="/nice-boy.jpg">
</div>

jquery codes:
`
window.loadCount = 0;
$('.imgTag').onload(function(){
    window.loadCount++;
    if(window.loadCount == $('.imgTag').length){
        $('.imgTag').show();
    }
});
`

Upvotes: 0

Related Questions