在 Javascript 中检测图像 404
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3019077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting an image 404 in Javascript
提问by Tobias Lütke
After a user uploads a file we have to do some additional processing with the images such as resizing and upload to S3. This can take up to 10 extra seconds. Obviously we do this in a background. However, we want to show the user the result page immediately and simply show spinners in place until the images arrive in their permanent home on s3.
用户上传文件后,我们必须对图像进行一些额外的处理,例如调整大小并上传到 S3。这最多可能需要 10 秒的额外时间。显然,我们在后台执行此操作。但是,我们希望立即向用户显示结果页面,并简单地显示旋转器,直到图像在 s3 上到达他们的永久主页。
I'm looking for a way to detect that a certain image failed to load correctly (404) in a cross browser way. If that happens, we want to use JS to show a spinner in it's place and reload the image every few seconds until it can be successfully loaded from s3.
我正在寻找一种方法来检测某个图像无法以跨浏览器的方式正确加载(404)。如果发生这种情况,我们希望使用 JS 在它的位置显示一个微调器并每隔几秒钟重新加载图像,直到它可以从 s3 成功加载。
采纳答案by unomi
From: http://lucassmith.name/2008/11/is-my-image-loaded.html
来自:http: //lucassmith.name/2008/11/is-my-image-loaded.html
// First a couple helper functions
function $(id) {
return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) { return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}
// Here's the meat and potatoes
function image(src,cfg) { var img, prop, target;
cfg = cfg || (isType(src,'o') ? src : {});
img = $(src);
if (img) {
src = cfg.src || img.src;
} else {
img = document.createElement('img');
src = src || cfg.src;
}
if (!src) {
return null;
}
prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
img.alt = cfg.alt || img.alt;
// Add the image and insert if requested (must be on DOM to load or
// pull from cache)
img.src = src;
target = $(cfg.target);
if (target) {
target.insertBefore(img, $(cfg.insertBefore) || null);
}
// Loaded?
if (img.complete) {
if (img[prop]) {
if (isType(cfg.success,'f')) {
cfg.success.call(img);
}
} else {
if (isType(cfg.failure,'f')) {
cfg.failure.call(img);
}
}
} else {
if (isType(cfg.success,'f')) {
img.onload = cfg.success;
}
if (isType(cfg.failure,'f')) {
img.onerror = cfg.failure;
}
}
return img;
}
And here how to use it:
以及如何使用它:
image('imgId',{
success : function () { alert(this.width); },
failure : function () { alert('Damn your eyes!'); },
});
image('http://somedomain.com/image/typooed_url.jpg', {
success : function () {...},
failure : function () {...},
target : 'myContainerId',
insertBefore : 'someChildOfmyContainerId'
});
回答by SLaks
Handle the <img>element's onerrorevent.
处理<img>元素的onerror事件。
回答by Dorathoto
First option:
第一个选项:
<img src="picture1.gif" onerror="this.onerror=null;this.src='missing.gif';"/>
Second option:
第二种选择:
<html>
<head>
<script type="text/javascript">
function ImgError(source){
source.src = "/noimage.gif";
source.onerror = "";
return true;
}
</script>
</head>
<body>
<img src="image_example1.jpg" onerror="ImgError(this)" />
</body>
</html>
PS: it's pure javascript! you don't need any libraries. (Vanilla JS)
PS:它是纯javascript!你不需要任何图书馆。(香草JS)
Example in Fidler
Fiddle 中的示例
回答by oasisfleeting
just bind the attr trigger on the error event.
只需在错误事件上绑定 attr 触发器。
$(myimgvar).bind('error',function(ev){
//error has been thrown
$(this).attr('src','/path/to/no-artwork-available.jpg');
}).attr('src',urlvar);
回答by Adam Mac
I just did
我已经做了
if ($('#img')[0].naturalWidth > 0) {
as i noticed there was no naturalWidth if the image 404'd.
因为我注意到如果图像 404'd 没有 naturalWidth 。
However, i can understand wanting to use a method above.
但是,我可以理解想要使用上述方法。
回答by dav1dhunt
This worked for me (mine is in coffeescript). You'll need to replace with a spinner instead, of course.
这对我有用(我的是咖啡脚本)。当然,您需要用微调器替换。
checkImages = ->
$("img").each ->
$(this).error ->
$(this).attr("src", "../default/image.jpg")
$(document).on('page:load', checkImages)
I'm guessing the javascript equivalent is something like
我猜 javascript 等价物类似于
function checkImages() {
$("img").each(function() {
$(this).error(function() {
$(this).attr("src", "../default/image.jpg");
});
});
};
$(document).on("page:load", checkImages);
$(document).on("page:load", checkImages);

