2012-08-17 68 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; 
}