image.orror事件从不触发,但image不't有效数据-需要解决
image.onError event never fires, but image isn't valid data - need a work around
我正在尝试使用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.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;
}
这是我的解决方案。如果我的图像有404,我会尝试插入一个200 OK的数组(纯Javascript)。图像必须在同一路径中。否则,myfunc将返回"no-image.png"。jQuery/JavaScript替换损坏的图像
相关文章:
- 如何有效地创建多维javascript数组
- Join架构验证:Join.object定义数组中的有效键
- 如何将数组转换为有效的json
- 使用Underscore.js修改json数组中所选元素的更有效方法
- 选择具有值数组的所有元素的最有效方法
- 如何以最有效的方式实现这个多维数组
- 数组在手动写入时有效,但从文本文件加载时无效
- 将javascript数组中的项移动到特定位置的有效方法
- Javascript:字符串中有效的基于数组的替换
- 将JS对象数组转换为嵌套形式的最有效方法
- JavaScript,数组和函数 - 只有数组的最后一个元素有效
- 筛选数字数组,其中 0 是有效输入
- 在JavaScript中搜索数组映射的最有效方法
- 在二维数组中搜索比嵌套循环更有效的方法
- 有效地串行化(并从nodejs读取)int数组
- Javascript-循环通过有效URL的数组's
- 从数组中删除的最有效方法
- 将非类型化数组编译为 C 的有效方法是什么?
- 在dom中构建一个基于image的数组
- 我想将一个Image标记数据传递给servlet.怎样