图像加载不适用于IE 8或更低版本 [英] Image load not working with IE 8 or lower

查看:98
本文介绍了图像加载不适用于IE 8或更低版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是检查图像是否已成功加载。它在现代浏览器中运行良好,但IE8或7是一个可怕的问题。下面是一个示例代码:

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. 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!

推荐答案

在设置<$之前,你必须设置 onload 处理程序c $ c> .src value。

You HAVE to set the onload handler BEFORE you set the .src value.

在某些版本的IE中,如果图像在浏览器缓存中,则加载事件将为设置 .src 值时立即触发。如果您的加载处理程序尚未到位,您将错过该事件。

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. If your load handler is not already in place, you will miss that event.

此外,旧版本的IE不支持 naturalWidth naturalHeight ,因此它们将始终未定义。而且,你应该使用 onerror onabort 以捕获错误条件。

Also, naturalWidth and naturalHeight are NOT supported in older versions of IE so they will always be undefined. And, you should use onerror and onabort to catch the error conditions.

没有必要使用jQuery这个。你可以这样做:

There's no need to use jQuery for this. 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';

这篇关于图像加载不适用于IE 8或更低版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆