2012-08-17 64 views
6

我的目標是檢查圖像是否已成功加載。它在現代瀏覽器中運行良好,但IE8或7是一個可怕的問題。下面是一個示例代碼:圖像加載不能與IE 8或更低版本

var img = new Image(), 
    url = 'http://something.com/images/something.gif'; 

    $(img).attr('src', url).load(function() { 
     if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { 
      alert('broken image!'); 
     } 
     else { 
      alert('successfully loaded'); 
     } 
    } 

任何人有任何的想法來解決這個問題?感謝advace!

回答

12

之前已設置了.src值設置onload處理程序。

在IE瀏覽器的某些版本中,如果圖像是在瀏覽器緩存,負載事件將立即當.src值設置解僱。如果您的裝載處理程序尚未就位,則會錯過該事件。

此外,naturalWidthnaturalHeight不支持IE的舊版本,因此它們將始終未定義。而且,你應該使用onerroronabort捕獲錯誤條件。

沒有必要爲此使用jQuery。你可以這樣做:

var img = new Image(), 

img.onload = function() { 
    alert("loaded successfully"); 
} 
img.onerror = img.onabort = function() { 
    alert("broken image"); 
} 
// only set .src AFTER event handlers are in place 
img.src = 'http://something.com/images/something.gif'; 
+0

在這種情況下,如果圖像已經裝入將再次加載,否則會從緩存中加載? – Sinal 2012-08-17 06:25:32

+0

如果指定先前已加載相同的URL,瀏覽器會從緩存中加載它。這就是緩存的重點。 – jfriend00 2012-08-17 06:34:26

+0

是的,我得到它在所有瀏覽器的工作現在。非常感謝 :-) – Sinal 2012-08-17 06:55:50

3

如果圖像被破壞,則onload事件不會被觸發,而是會觸發onerror事件。所以,你需要做的是這樣的:

var img = new Image(), 
url = 'http://something.com/images/something.gif'; 

img.onload = function() { 
    alert('successfully loaded'); 
}; 

img.onerror = function() { 
    alert('broken image!'); 
}; 

$(img).attr('src', url); 

或者使用jQuery:

$(img).load(function() { 
    alert('successfully loaded'); 
}).error(function() { 
    alert('broken image!'); 
}).attr('src', url); 
+0

謝謝,但我不知道爲什麼在Chrome和Firefox瀏覽器工作良好,當圖像被成功加載我得到警報。假設圖像是好的,你還有什麼建議嗎? – Sinal 2012-08-17 05:10:15

+0

歡迎來到瀏覽器不一致的真實世界。應付他們。 – nalply 2012-08-17 05:12:13

1
var url="http://something.com/images/something.gif", 
    img=new Image; 
img.onload=img.onerror=function(ev){ 
    if(ev.type=="load")alert("successfully loaded"); 
    else if(ev.type=="error")alert("error loading"); 
} 
img.src=url; 
// If image is cached then no `onload` or `onerror` can occur. 
if(img.complete){ 
    alert("successfully loaded"); 
    img.onload=img.onerror=null; 
}