2013-05-10 54 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

相關問題