1

(not duplicate, because 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="https://unsplash.it/200/300/">
<img src="https://unsplash.it/200/300/">
<img src="https://unsplash.it/200/300/">
</div>

Execute below js when all images completely loaded

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


Tried this js :
But not works properly on my site, problem is when i clear browser cache, then it works/execute! when i reload page then next time it's not works/execute!
It only works when i clear browser cache.

var img = $('.main-slider img')
var count = 0
img.each(function(){
  $(this).load(function(){
    count = count + 1
    if(count === img.length) {
      $('.main-slider').removeClass('my-loader').addClass('visible')
    }
  });
});

Any simple solution? Thanks in advance.

Aariba
  • 1,104
  • 5
  • 17
  • 47

2 Answers2

1

jQuery provides a way to register a callback for the window load event which will fire when the entire page, including images and iframes, are loaded. Reference: https://learn.jquery.com/using-jquery-core/document-ready/

Your code should look something like:

$( window ).load(function () {
  var img = $('.main-slider img')
  var count = 0
  img.each(function(){
    $(this).load(function(){
      count = count + 1
      if(count === img.length) {
        $('.main-slider').removeClass('my-loader').addClass('visible')
      }
    });
  });
});
  • Is correct but at this point it is no longer necessary to check whether the images have been loaded, simply remove the class in the event "window.load". – Baro Oct 01 '16 at 14:12
1

Here's how to do this, using Deferreds and native handlers, and calling the onload handler if the image is cached in older browsers etc.

var img  = $('.main-slider img');
var defs = img.map(function(){
    var def = new Deferred();

    this.onload  = def.resolve;
    this.onerror = def.reject;
    if (this.complete) this.onload();

    return def.promise();
});

$.when.apply($, defs).then(function() {
    $('.main-slider').removeClass('my-loader').addClass('visible')
});
adeneo
  • 293,187
  • 26
  • 361
  • 361