image.orror事件从不触发,但image不't有效数据-需要解决

image.onError event never fires, but image isn't valid data - need a work around

本文关键字:image 有效数 有效 数据 解决 事件 orror      更新时间:2023-09-26

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

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

用户必须经过身份验证才能看到此图像,如果没有,我希望显示一条错误消息。不幸的是,服务器没有返回HTTP错误消息,而是将请求重定向到一个(大部分)空页面,因此我得到了一个HTTP 200,但警告Resource interpreted as Image but transferred with MIME type text/html,并且没有显示任何内容。

我该如何处理这个案子?如果用户未通过身份验证,我就无法更改Web服务器的服务。

image.onload事件侦听器中,检查image.widthimage.height是否都为零(最好是image.naturalWidthimage.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;
}

这是我的解决方案。如果我的图像有404,我会尝试插入一个200 OK的数组(纯Javascript)。图像必须在同一路径中。否则,myfunc将返回"no-image.png"。jQuery/JavaScript替换损坏的图像