Javascript jQuery Ajax用图像加载HTML内容,如何检查是否加载了所有图像?

Javascript jQuery Ajax用图像加载HTML内容,如何检查是否加载了所有图像?,javascript,jquery,dom,javascript-events,Javascript,Jquery,Dom,Javascript Events,我正在为我的站点编写无限滚动脚本: $(window).scroll(function(){ if($(window).scrollTop() == $(document).height() - $(window).height()){ ... $.ajax({ ... success: function(json) {if(json.success){ ... // here I append an Ajax @res

我正在为我的站点编写无限滚动脚本:

$(window).scroll(function(){
  if($(window).scrollTop() == $(document).height() - $(window).height()){
    ...
    $.ajax({
      ...
      success: function(json) {if(json.success){
        ...
        // here I append an Ajax @response with a new element to my existing HTML
        $("#mindIndexSummaryFirst").append(json.items1);
        $("#mindIndexSummarySecond").append(json.items2);
        $("#mindIndexSummaryThird").append(json.items3);
        // here I try to check whether all images are loaded
        $("#mindIndexSummary img").on('load', function(){
          // and I need to call two functions on loaded element
          // hoverImg() need the loaded image to calculate the height
          $('.pi-hover-img'+json.course).hoverImg();
          $(".popup3").tooltip();
        });
      }
    ...
  });
加载的HTML元素如下所示:

<div class="page-item pi-hover-img  pi-normal">
  <a class="overlayPop" href="#">
  <a class="item_uri" id="course153" href="#">
    <img src="/public/file/course/image/153-course.png" class="pi-item-image">
  </a>
  <a href="#" class="popup5 hide-text" style="display: none;">
    <img src="/public/file/account/image/282-user.jpeg" class="item_image">
  </a>
  <a class="popup action-button big_interested " id="course_153" href="javascript:;" style="top: -162.5px; left: 83.5px; display: none;"> Mi interessa</a>
  <a href="javascript:;">Description</a>
  <a class="popup4 hide-text" href="javascript:;">Preview</a>
  <span class="popup2" style="display: none;">1€</span>
  <a href="/course/153/gestire-un-pubblico">
    <h2 style="top: 320px;">Gestire un pubblico</h2>
    <span class="rfloat pi-icon">
      <img src="/public/img/site_icon/video_course_black.png">
    </span>
    <div class="clearfix"></div>
  </a>
</div>

1€
我加载了5个元素,15个图像,但可能加载的元素更少

问题是我的函数被调用了不止一次(我用alert测试了这一点),并且我不确定函数是否在图像加载后被调用

如果有人有同样的情况,请给我一些建议

将处理程序附加到与查询匹配的每个图像上,这样每个图像在加载时都会启动函数,而不是在所有图像加载完成时启动一次

您必须跟踪已加载的图像,以便说明它们是否已全部加载

大致如下:

var noOfImages = $("#mindIndexSummary img").length;
var noLoaded = 0;

$("#mindIndexSummary img").on('load', function(){ 

    noLoaded++;
    if(noOfImages === noLoaded) {
        handleAllLoaded();
    }

});

这是我在类似情况下使用的解决方案的粗略版本<每次执行
load
方法时,都会更新code>numload,该方法允许您检查预测(
numImage
)是否等于加载的图像总量

var img =  $( '#mindIndexSummary' ).find( 'img' )
  , numImage = img.length;

img.on( 'load', function(){

    var self = $( this )
      , numLoaded  = self.attr( 'data-loaded', true ).length;

    self.attr( 'data-loaded', true );

    if( numImages === numLoaded ) 

    funcToCall();   


});
此外,您还可以更进一步,在父元素上设置
data
属性,这将允许您根据其值触发/终止其他事件

var parent = $( '#mindIndexSummary' )
  , img =  $( '#mindIndexSummary' ).find( 'img' )
  , numImage = img.length;

img.on( 'load', function(){

    var self = $( this )
      , numLoaded  = self.attr( 'data-loaded', true ).length;

    parent.attr( 'data-load', 'loading' );
    self.attr( 'data-loaded', true );

    if( numImages === numLoaded ) 

    parent.attr( 'data-load', 'complete' );
    funcToCall();   


});

if( parent.attr('data-load').slice( 0, 7 ) === 'loading' )
do something else

图像上的加载事件有点不可靠(请参阅Jquery文档)。 也就是说,可以通过在每个选定的图像上单独检查加载事件来组装解决方案。图像很可能在执行时被缓存或已加载。在这种情况下,图像元素应该有一个“.complete”属性

我制作了一个小的jQuery插件来说明这种方法(还有更完整的插件):

插件接受带有两个回调的哈希,一个在每次加载图像时触发(图像作为参数传递),另一个在加载所有图像时触发(图像数组作为参数传递)

它并没有完成所有的怪癖,但它应该给你一个大致的想法。
我在上做了一个小演示。

这是一个如何创建全局变量(数组)的描述,该变量将跟踪加载的每个图像。这样,您可以使用回调函数主动检查何时加载所有图像

var image_state_array = new Array(false, false, false, false, false, false, false, false, false, false);
阵列中的每个位置都将跟踪已加载的图像。因此,例如,如果10个图像列表中的图像2已加载,则数组将如下所示(请记住数组索引从0开始):

假设您有一个基于某些用户交互动态重新加载的图像列表(例如,用户单击“刷新”以获取一组新的图像供选择)。加载所有图像后,您希望提醒用户图像已加载(或调用其他类型的函数)。首先为即将加载的映像设置onload事件

//get image 0

var image = document.getElementsByClassName("search_images")[0];

//track the image load state 

image.onload = function(){
      trackImageLoadState(0); //note that 0 is the image index from the list of elements 
}
接下来,按照通常的方式设置图像源。这将触发onload偶数并调用函数

//set the source of the image, 

    image.src = desireImagePNG;
跟踪图像加载状态将添加图像已加载到图像\u状态\u数组,跟踪图像0已加载的图像。在记录image0已加载后,它循环遍历image_state_数组并计算已加载的返回图像的数量。如果加载了足够多的图像,它将执行您试图实现的任何功能。在本例中,我淡出了加载屏幕

    function trackImageLoadState(numImage){
      //debug print
      //console.log("numImage: " + numImage);

      //set the array image value to true of the passed in index 
      image_state_array[numImage] = true;

      //debug print
      //console.log("image_state_array[numImage] " + image_state_array[numImage] );

      var loadedImagesCount = 0;

      //loop through the array and count the amount of images that have loaded
      for(var counter2 = 0; counter2 < image_state_array.length; counter2++){
        //debug print
        //console.log("image_state_array[counter] " + image_state_array[counter2] + "counter" + counter2 );

        if(image_state_array[counter2]){
          loadedImagesCount++;
        }
      }

      //debug print
      //console.log("loadedImagesCount: " + loadedImagesCount);

      //if the amount of images required to be loaded has been met, execute function. If you want to know when all images have been loaded, you need to set the if statement condition to the total count of images. For example:
if(loadedImagesCount>10){} if you have 10 images. 

  if(loadedImagesCount>5){

    //fade out the loading screen - any other function will work here as well
    fadeOutMainLoadingScreen();

  }

}
函数trackImageLoadState(numImage){
//调试打印
//log(“numImage:+numImage”);
//将传入索引的数组图像值设置为true
图像状态数组[numImage]=true;
//调试打印
//log(“图像状态数组[numImage]”+图像状态数组[numImage]);
var LoadedImageScont=0;
//循环遍历数组并计算已加载的图像数量
for(var counter2=0;counter210){}如果您有10个图像。
如果(加载图像>5){
//淡出加载屏幕-任何其他功能也将在此处工作
淡出InLoadingScreen();
}
}
请记住,每次再次调用操作时都必须重置全局变量。这可以按如下所示进行:

//reset the global variable array to track the new load of images 

for(var i = 0; i < image_state_array.length; i++){
  image_state_array[i] = false;
}
//重置全局变量数组以跟踪图像的新加载
对于(变量i=0;i

这是通过回调函数和全局变量跟踪已加载图像的有效方法。请评论,因为我知道它可能会得到改进,变得更具活力。谢谢

加载事件处理程序不适用于您?每次图像加载($(“#mindIndexSummary img”)都会触发加载。长度时间@FritsvanCampen是的,它可以工作,现在我解决了问题,感谢您的回答:)@Sushil,是的,现在我明白了:)非常感谢:)我通过对代码的一些更改来解决问题:当我加载新元素时,我在其中添加了另一个id$('.pi hover img'+json.course)“json.course”对任何新加载的元素都有什么更改。事实上,如果我检查所有图像$(“#mindIndexSummary img”).length;我有一些al图像加载到previus。但是我需要新加载的图像的数量,我可以用我添加的id获得这个数字:var noOfImages=$('.pi hover img'+json.course+“img”).length;谢谢你,伙计!但在我的c
//get image 0

var image = document.getElementsByClassName("search_images")[0];

//track the image load state 

image.onload = function(){
      trackImageLoadState(0); //note that 0 is the image index from the list of elements 
}
//set the source of the image, 

    image.src = desireImagePNG;
    function trackImageLoadState(numImage){
      //debug print
      //console.log("numImage: " + numImage);

      //set the array image value to true of the passed in index 
      image_state_array[numImage] = true;

      //debug print
      //console.log("image_state_array[numImage] " + image_state_array[numImage] );

      var loadedImagesCount = 0;

      //loop through the array and count the amount of images that have loaded
      for(var counter2 = 0; counter2 < image_state_array.length; counter2++){
        //debug print
        //console.log("image_state_array[counter] " + image_state_array[counter2] + "counter" + counter2 );

        if(image_state_array[counter2]){
          loadedImagesCount++;
        }
      }

      //debug print
      //console.log("loadedImagesCount: " + loadedImagesCount);

      //if the amount of images required to be loaded has been met, execute function. If you want to know when all images have been loaded, you need to set the if statement condition to the total count of images. For example:
if(loadedImagesCount>10){} if you have 10 images. 

  if(loadedImagesCount>5){

    //fade out the loading screen - any other function will work here as well
    fadeOutMainLoadingScreen();

  }

}
//reset the global variable array to track the new load of images 

for(var i = 0; i < image_state_array.length; i++){
  image_state_array[i] = false;
}