【问题标题】:image.onError event never fires, but image isn't valid data - need a work aroundimage.onError 事件永远不会触发,但图像不是有效数据 - 需要解决
【发布时间】:2012-04-06 05:33:04
【问题描述】:

我正在尝试使用 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 并没有显示任何内容。

我该如何处理这种情况?如果用户未通过身份验证,我无法更改网络服务器提供的内容。

【问题讨论】:

    标签: javascript error-handling mime-types


    【解决方案1】:

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

    【讨论】:

    • 附言。 document.appendChild 是无效呼叫。 document 不是节点,因此您不能将元素附加到它。要在文档中插入图像,请使用document.body.appendChild
    • 谢谢,这就是我实际上正在做的事情,只是不小心把它漏掉了。 :)
    • 仅供参考:这些检查在 Internet Explorer 中对 SVG 图形失败,因为您检查的所有值都是 0。 :-(
    • 鉴于这个问题的日期,我仍然会求助于onerror,请参阅:javascript.info/onload-onerror#other-resources
    【解决方案2】:

    这是我的解决方案。如果我的图像有 404 - 我尝试插入一个 200 OK(纯 Javascript)的数组。图像必须在同一路径中。否则 - 我的函数将返回“no-image.png”。 jQuery/JavaScript to replace broken images

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 2011-11-19
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多