2013-05-10 61 views
3

我做了我的网站无限滚动的脚本:jQuery Ajax使用图像加载HTML内容,如何检查是否加载了所有图像?

$(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> 

我加载5元,15幅图像,但有一种可能性,即加载的元素更少。

问题是我的函数被多次调用(我用alert来测试),并且我不确定该函数是否在图像加载后调用。

如果有人有同样的情况,请给我一些建议(P.S我为我的坏英语道歉)。

+0

加载事件处理程序不适合你吗? – Halcyon 2013-05-10 15:36:14

+1

加载将触发每个图像加载($(“#mindIndexSummary img”)。长度时间) – Anoop 2013-05-10 15:40:26

+0

@FritsvanCampen是它的工作,现在我解决问题谢谢回答:) – 2013-05-12 20:01:31

回答

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

将附加的处理程序,以每个匹配查询图像的 - 因此它被加载后,每个图片将触发功能 - 不是一次,当所有装载完毕。

您将不得不跟踪已加载的图像,以说明它们是否全部加载。

线沿线的:

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

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

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

}); 
+0

非常感谢你:)我解决了一些你的代码变化的问题: 当我加载一个新的元素,我把它放在另一个ID $('。pi-hover-img'+ json.course)“json.course “任何新加载的元素发生了什么变化。 事实上,如果我检查所有图像$(“#mindIndexSummary img”)。我有一些加载previus的图像。但我需要更新的加载图片的数量,我可以通过添加我的id来获得这个数字:var noOfImages = $('。pi-hover-img'+ json.course +“img”)。 – 2013-05-12 17:41:52

0

这是我在类似情况下使用的解决方案的一个粗略的版本。每次执行load方法时,会更新numLoaded,这样您可以检查预测(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 
+0

谢谢你的回答,我解决了问题:) – 2013-05-12 17:42:38

0

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

我做了一个小jQuery插件,示出的方法(有更完整的人反正):

(function($) { 
    $.fn.imagesLoaded = function(options) { 
     var images = this.find("img"), 
      loadedImages = [], 
      options = options; 

     images.each(function(i, image) { 
      function loaded() { 
       loadedImages.push(this); 
       if(options.imageLoaded) { 
        options.imageLoaded(this);  
       } 
       if(loadedImages.length == images.length) { 
        if(options.complete) { 
         options.complete(loadedImages);  
        } 
       } 
      } 

      if(image.complete || image.complete === undefined) { 
       // Image is already loaded 
       loaded.call(image);    
      } else { 
       // Image is not loaded yet, bind event 
       $(image).load(loaded); 
      } 
     }); 
    } 
})(jQuery); 

插件接受带有两个回调各一个的图像被加载时烧制(图像的哈希作为参数传递),另一个是所有图像都已加载(图像数组作为参数传递)。

$("#element-containing-images").imagesLoaded({ 
    imageLoaded: function(image) { 
     console.log("Image loaded:", image); 
    }, 
    complete: function(images) { 
     console.log("All images loaded:", images); 
    } 
}); 

这不是所有的怪癖完成,但它应该给你一个大概的想法。 我在http://jsfiddle.net/GYJGK/进行了一个小演示。

+0

谢谢你的回答,我解决了问题:) – 2013-05-12 17:42:23

0

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

var image_state_array = new Array(false, false, false, false, false, false, false, false, false, false); 

数组中的每个位置都会跟踪哪个图像已加载。所以对于如果图像2中10张名单已经加载例如数组是这样的(记住数组的索引从0开始):

var image_state_array = new Array(false, false, true, false, false, false, false, false, false, false); 

比方说你有一个图像列表,你是动态重装基于某些用户交互(例如用户单击刷新以获取一组新图像以供选择)。一旦所有图像加载完毕,您都希望提醒用户图像已加载(或调用某种其他类型的功能)。首先为即将加载的图像设置一个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; 

跟踪图像加载状态将添加图像已加载到image_state_array,跟踪image0已加载。在它记录了image0已加载后,它会遍历image_state_array并计算已加载的返回图像的数量。如果足够的图像已经加载,它会执行你想要实现的任何功能。在这个例子中,我淡出了一个加载屏幕。

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

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

+0

谢谢你!但在我的情况下,我更喜欢使用jquery或跟踪整个加载的东西,因为我不知道或需要做一些事情来了解我必须加载的图像数量。 – 2017-03-17 18:09:20