image.onError事件永远不会触发,但图像不是有效数据 - 需要解决

Chr*_*ski 18 javascript error-handling mime-types

我正在尝试使用JavaScript将图像附加到页面:

image = document.createElement('img');
image.onload = function(){
    document.body.appendChild(image);
}
image.onerror = function(){
    //display error
}
image.src = 'http://example.com/image.png';
Run Code Online (Sandbox Code Playgroud)

必须对用户进行身份验证才能看到此图像,如果不是,我想显示错误消息.不幸的是,服务器没有返回HTTP错误消息,而是将请求重定向到(大多数)空页面,所以我得到了一个HTTP 200,但警告Resource interpreted as Image but transferred with MIME type text/html并没有显示任何内容.

我该如何处理这个案子?如果用户未经过身份验证,我无法更改Web服务器所提供的内容.

Rob*_*b W 41

在image.onload事件侦听器,检查是否image.width和image.height均为零(优选image.naturalWidth和image.naturalHeight,当它们支持).

如果宽度和高度都为零,则图像被视为无效.

演示:http://jsfiddle.net/RbNeG/

// Usage:
loadImage('notexist.png');

function loadImage(src) {
    var image = new Image;
    image.onload = function() {
        if ('naturalHeight' in this) {
            if (this.naturalHeight + this.naturalWidth === 0) {
                this.onerror();
                return;
            }
        } else if (this.width + this.height == 0) {
            this.onerror();
            return;
        }
        // At this point, there's no error.
        document.body.appendChild(image);
    };
    image.onerror = function() {
        //display error
        document.body.appendChild(
            document.createTextNode('\nError loading as image: ' + this.src)
        );
    };
    image.src = src;
}
Run Code Online (Sandbox Code Playgroud)

  • PS.`document.appendChild`是一个无效的调用.`document`不是一个节点,所以你不能附加一个元素.要在文档中插入图像,请使用`document.body.appendChild`. (2认同)