简体   繁体   English

图像加载不适用于IE 8或更低版本

[英]Image load not working with IE 8 or lower

I am aiming to check if image has been loaded successfully. 我的目标是检查图像是否已成功加载。 It has been working well in modern browsers but IE8 or 7 it is a terrible issue. 它在现代浏览器中运行良好,但IE8或7是一个可怕的问题。 Here is a sample code: 这是一个示例代码:

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');
        }
    } 

Anyone has any idea to work around with this issue? 任何人都有任何想法解决这个问题? Thanks in advace! 谢谢你的推荐!

You HAVE to set the onload handler BEFORE you set the .src value. 您必须在设置.src值之前设置onload处理程序。

In some versions of IE, if the image is in the browser cache, the load event will be fired immediately when the .src value is set. 在某些版本的IE中,如果图像位于浏览器缓存中,则在设置.src值时将立即触发load事件。 If your load handler is not already in place, you will miss that event. 如果您的装载处理程序尚未到位,您将错过该事件。

Also, naturalWidth and naturalHeight are NOT supported in older versions of IE so they will always be undefined. 此外,旧版本的IE不支持naturalWidthnaturalHeight ,因此它们将始终未定义。 And, you should use onerror and onabort to catch the error conditions. 并且,您应该使用onerroronabort来捕获错误条件。

There's no need to use jQuery for this. 没有必要为此使用jQuery。 You can just do this: 你可以这样做:

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';

If the image is broken, then onload event won't be fired, instead, the onerror event will be fired. 如果图像被破坏,则不会触发onload事件,而是会触发onerror事件。 So you need to do like this: 所以你需要这样做:

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);

Or with jQuery: 或者使用jQuery:

$(img).load(function() {
  alert('successfully loaded');
}).error(function() {
  alert('broken image!');
}).attr('src', url);
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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM