简体   繁体   English

在所有图像加载失败后执行js

[英]Execute js after all image loaded not working

(not duplicate, because not find exactly/easy solution) (不重复,因为找不到确切/容易的解决方案)
I'm trying to execute JS after all images completely loaded. 所有图像完全加载后,我正在尝试执行JS。 My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div. 我的目标是,当所有图像完成完全加载后,然后对main-slider div visible removeClass my-loader和addClass。

HTML: 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 当所有图像完全加载后,在js下执行

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


Tried this js : 尝试过这个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. 提前致谢。

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. jQuery提供了一种注册窗口加载事件的回调的方法,该事件将在加载整个页面(包括图像和iframe)时触发。 Reference: https://learn.jquery.com/using-jquery-core/document-ready/ 参考: 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')
      }
    });
  });
});

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. 这是使用Deferreds和本机处理程序的方法,如果图像在较旧的浏览器等中缓存,则调用onload处理程序。

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')
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM