2010-03-06 94 views
9

我看到了a comment on Ben Nadel's blog其中Stephen Rushing發佈了一個loader,但我無法弄清楚如何通過選擇器和參數..我想我還需要一個completeCallback & errorCallback函數?jQuery加載完整回調圖像

function imgLoad(img, completeCallback, errorCallback) { 
    if (img != null && completeCallback != null) { 
     var loadWatch = setInterval(watch, 500); 
     function watch() { 
      if (img.complete) { 
       clearInterval(loadWatch); 
       completeCallback(img); 
      } 
     } 
    } else { 
     if (typeof errorCallback == "function") errorCallback(); 
    } 
} 
// then call this from anywhere 
imgLoad($("img.selector")[0], function(img) { 
    $(img).fadeIn(); 
}); 

HTML:

<a href="#" class="tnClick" ><img id="myImage" src="images/001.jpg" /></a> 

JS:

$(document).ready(function() { 
    var newImage = "images/002.jpg"; 
    $("#myImage").css("display","none"); 
    $("a.tnClick").click(function() { 
     // imgLoad here 
    }); 
}) 
+0

您想要做什麼,在顯示之前預先加載圖像? – 2010-03-06 12:25:20

+0

其實我只是希望它淡入.. 當我點擊圖片時,將它設置爲none並加載。 加載完成後,淡入 – FFish 2010-03-06 12:30:49

回答

40

如果你想讓它顯示之前加載,你可以修剪下來很多,像這樣:

$(document).ready(function() { 
    var newImage = "images/002.jpg"; //Image name 

    $("a.tnClick").click(function() { 
     $("#myImage").hide() //Hide it 
     .one('load', function() { //Set something to run when it finishes loading 
      $(this).fadeIn(); //Fade it in when loaded 
     }) 
     .attr('src', newImage) //Set the source so it begins fetching 
     .each(function() { 
      //Cache fix for browsers that don't trigger .load() 
      if(this.complete) $(this).trigger('load'); 
     }); 
    }); 
}); 

.one()電話確認.load()只會觸發一次,所以沒有重複的淡入。 .each()最後是因爲某些瀏覽器不會爲從緩存中提取的圖像觸發load事件,這就是您發佈的示例中的輪詢也試圖做的。

+0

Ooooh「緩存修復瀏覽器不會觸發.load()」 這是我關心的問題(閱讀後) 你知道哪些瀏覽器不支持.load嗎? – FFish 2010-03-06 12:41:15

+0

甜美的尼克,非常感謝! – FFish 2010-03-06 12:44:51

+0

@FFish - 歡迎光臨!回答你的另一個問題:我知道的瀏覽器是Opera,Firefox,IE ......但這可能不是整個列表。 – 2010-03-06 12:51:11

0

試試這個嗎?

doShow = function() { 
    if ($('#img_id').attr('complete')) { 
    alert('Image is loaded!'); 
    } else { 
    window.setTimeout('doShow()', 100); 
    } 
}; 

$('#img_id').attr('src', 'image.jpg'); 
doShow(); 

好像上述作品無處不在...

4

,因爲如果在圖像瀏覽器的緩存和IE(據我所知)的Chrome發現您需要小心使用Load事件圖像時不會像預期的那樣觸發事件。

因爲我自己不得不面對這個問題,所以我通過檢查DOM屬性complete(據說可以在大多數主流瀏覽器中工作)來解決:如果等於true,我只是解除了先前綁定的'load'事件。見例如:

$("#myimage").attr("src","http://www.mysite.com/myimage.jpg").load(doSomething); 

if ($("#myimage").get(0).complete) { 

    // already in cache? 
      $("#myimage").unbind("load"); 
      doSomething(); 


} 

希望這有助於

1

我想這個功能肯定不希望在頁面呈現時加載的所有圖像。我的圖片在亞馬遜S3上,並有一個大的照相館,這將是很多不必要的要求。我創建了一個快速的jQuery插件來處理它here

$("#image-1").loadImage('/path/to/new/image.jpg',function(){ 
    $(this).css({height:'120px'});//alter the css styling after the image has loaded 
}); 

因此,基本上,只要用戶點擊該代表一組圖片的縮略圖,我加載在該點的其他圖像中的時間。回調允許我在加載圖像後更改css。