2010-08-21 64 views

回答

105

可以使用.load()事件處理程序,如下所示:

$("#myImg").load(function() { 
    alert('I loaded!'); 
}).attr('src', 'myImage.jpg'); 

務必之前將其附加設置源,或者該活動可能已解僱你附加的處理程序之前,聽它(例如從緩存中加載)。

如果這可行的(設置綁定後src),一定要檢查它的加載和啓動它自己,是這樣的:

$("#myImg").load(function() { 
    alert('I loaded!'); 
}).each(function() { 
    if(this.complete) $(this).load(); 
}); 
+0

是否有可能做到這一點:'$( 「#myImg」)生活( 「裝載」,函數(){//舞});'」 – 2010-08-21 14:14:16

+4

可惜。 ,'.load()'從jQuery v1.8開始已棄用 – SquareCat 2013-10-19 23:29:49

+26

@CummanderCheckov由於事件處理程序和ajax內容獲取器之間的不確定性而被棄用,在上面的代碼中只需替換'.load(' 'load','等於1.7+的功能。 – 2013-10-19 23:52:53

18

這只是簡單使用普通的JavaScript:

// Create new image 
var img = new Image(); 

    // Create var for image source 
var imageSrc = "http://example.com/blah.jpg"; 

    // define what happens once the image is loaded. 
img.onload = function() { 
    // Stuff to do after image load (jQuery and all that) 
    // Within here you can make use of src=imageSrc, 
    // knowing that it's been loaded. 
}; 

    // Attach the source last. 
    // The onload function will now trigger once it's loaded. 
img.src = imageSrc; 
+2

檢查已經存在於緩存中的圖像時會失敗。 – vsync 2014-04-07 17:27:59

4

我一直也在研究這個了很長一段時間,並已發現這個插件奇妙 幫助,這:https://github.com/desandro/imagesloaded

這似乎是一個很大的代碼,但是...我發現沒有其他方式來檢查圖像何時加載。

4

在('load')函數上使用jQuery是檢查圖像是否被加載的正確方法。但請注意,如果圖像已經在緩存中,on('load')函數將不起作用。

var myImage = $('#image_id'); 
//check if the image is already on cache 
if(myImage.prop('complete')){ 
    //codes here 
}else{ 
    /* Call the codes/function after the image is loaded */ 
    myImage.on('load',function(){ 
      //codes here 
    }); 
} 
0

,我認爲這可以幫助你一點:

$('img').error(function(){ 
     $(this).attr(src : 'no_img.png'); 
}) 

所以,如果加載 - 將顯示原始圖像。在其他 - 將顯示圖像,其中包含事實與崩潰的圖像或404 HTTP頭。

1

這很容易使用jQuery:

$('img').load(function(){ 
    //do something 
}); 

如果有試了一下:

$('tag')html().promise().done(function(){ 
    //do something 
}) ; 

,但不會檢查圖像是否爲負載。如果代碼被加載,那就完成了。否則,您可以檢查代碼是否已完成,然後觸發img加載函數並檢查圖片是否真正加載。所以,我們做兩者的結合:

$('tag')html('<img src="'+pic+'" />').promise().done(function(){ 
    $('img').load(function(){ 
    //do something like show fadein etc... 
    }); 
}) ;