2009-08-10 46 views
18

如果我有一盞明燈:JavaScript的:知道什麼時候圖像滿載

<img src="http://example.com/beacon" /> 

我想被調用一次信標請求完成的方法。例如:

<script> 
    $("img.beacon").load(function() { 
     // do stuff knowing the beacon is done 
    }); 
</script> 

這可能嗎?它在jQuery中嗎?

回答

32

當然。記住加載需要在src屬性之前添加。

$('<img />').load(function(){ 
    console.log('loaded'); 
}).attr('src', imgUrl); 

如果您已經定義那麼你堅持在窗口加載事件觸發,以確保圖像已回落電線在標記圖像標籤。

+0

請更正鏈接,因爲它鏈接到這個答案... – 2009-11-08 13:14:26

0

另一種選擇,如果它適合你:onload event在頁面或圖像加載後立即出現。

如:

<img ... onload="alert('test');" /> 
+2

但它的jQuery,不顯眼。內聯js事件是一個no no – redsquare 2009-08-10 21:57:23

17
$('img.beacon').load() 

不會永遠正確工作,ussually我這樣做:

$.fn.imageLoad = function(fn){ 
    this.load(fn); 
    this.each(function() { 
     if (this.complete && this.naturalWidth !== 0) { 
      $(this).trigger('load'); 
     } 
    }); 
} 

上面的代碼還涵蓋了形象腳本之前完成加載的情況下被執行。在標記中定義圖像時會發生這種情況。

使用這樣的:

<img src='http://example.com/image.png' class='beacon' /> 
<script type='text/javascript'> 
$(document).ready(function(){ //document.ready not really necessary in this case 
    $('img.beacon').imageLoad(function(){ 
     //do stuff 
    }); 
}); 
</script> 
+3

爲什麼$(this).get(0).naturalWidth而不是this.naturalWidth? – redsquare 2009-08-10 21:53:34

+0

@redsquare,好點,從來沒有真的雖然這一點。(改變了,但未經測試(雖然它應該只是工作)) – 2009-08-10 21:55:24

+0

啊好。你通過大量的鍵盤;) – redsquare 2009-08-10 21:56:44

0

您可以使用onload事件,火災時,整個頁面加載完畢。

$(window).load(function(){ 
    //everything is loaded 
}); 
3
<script type="text/javascript"> 
    $().ready(function() { 

     $('img#beacon').attr('src', 'http://sstatic.net/so/img/so/logo.png') 
      .load(function() { alert('Image Loaded'); }) 
      .error(function() { alert('Error Loading Image'); }); 
    }); 
    </script> 

這將加載標誌#1。

如果加載成功,警報('Image Loaded');執行

如果失敗,警報('Error Loading Image');執行

當然,其中任何一個都可以替換爲您自己的功能。

作爲新用戶,它拒絕了我的圖片標籤;但圖片標籤應該只包含id ='beacon'屬性;除非你想添加一個類。我們在代碼中設置'src'屬性,通常情況下,您要監視完成的圖像具有以編程方式設置的src值。

+0

謝謝sooo,它的工作;) – 2017-10-25 04:38:44

1

這裏有一個簡單的JavaScript代碼能夠在所有瀏覽器上運行:

var myImage = new Image(); 

myImage.onload = function() { 
    var image_width = myImage.width; 
    var image_height = myImage.height; 
    $('#pictureEl').html('<img width="'+ image_width +'" height="'+ image_height +'" src='+ myImage.src + '></img>');   
}; 

myImage.src = myUrl; 

一個jQuery的片斷必須做同樣的事情,引擎蓋下。

+0

I不要認爲它是這樣做的,但你可以自己檢查出來......並且按照你做這件事的方式來做這件事顯然是錯誤的。你不使用事件綁定,這是**正確的事件處理方式。 – 2009-11-08 13:13:02

+0

這絕對不適用於所有瀏覽器,這就是爲什麼我在這裏。在linux和mac上以及在默認的android瀏覽器中失敗,這實際上是我迄今爲止嘗試過的所有瀏覽器。 – schwiz 2013-02-14 06:51:12

+0

我正在尋找myImage.onload()函數... – jsleuth 2013-12-03 00:15:43

相關問題