Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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

Post a Comment for "Execute Js After All Image Loaded"