我正在从服务器加载图像,当存在404时返回图像。也就是说,如果我正在加载的图像不存在,服务器将返回带有200x200 PNG后备图像的404响应“照片不可用”就可以了。
我想检测客户端发生这种情况的时间。我尝试了onerror
属性:
<img src="http://example.com/photo.jpg" onerror="console.log(this)" />
此代码仅在服务器的404响应完全没有图像时有效。由于我的404响应确实存在,onerror
事件永远不会被触发。
有没有解决这个问题的方法,没有用JavaScript预加载图像?
答案 0 :(得分:1)
(更新了,因为@Brad指出了我无知的明显细节。)
我偶然发现this似乎正确触发了onerror():
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.errimg = function(options) {
return this.each(function() {
if (this.tagName.toLowerCase() != 'img')
return;
// store current img for error reference
var $_orig = $(this);
// create "production" image
var $newImg = $_orig.clone()
.attr('src', $_orig.data('src') || '')
.one('error', function() {
$(this).parent()
.empty()
.append($_orig);
});
// replace current img
$_orig.parent().empty().append($newImg);
});
};
})(jQuery);
$(function() {
$('.js_img img').errimg();
});
</script>
</head>
<body class="js_img">
<img id="testimgbad" src="http://img4.homefinder.com/i/00000000-0000-0000-0000-000000000000/w200-h-q" onerror="console.log('errored out');" />
</body>
</html>
答案 1 :(得分:0)
我采取的解决方法是通过 ajax 调用内部方法,该方法使用 httpclient 检查图像是否返回 404 预制页面。如果是(任何状态 404),则返回我自己的匿名图像,如果不是,则返回字符串本身。
答案 2 :(得分:-1)
一种解决方案是在服务器上找不到目标图像时不返回图像。相反,稍后使用onerror事件显示错误图像。
<img src="tttttttt.png" onerror="this.onerror=null;this.src='https://www.google.com/images/srpr/logo11w.png'" />
答案 3 :(得分:-1)
U可能会使用 onload 函数而不是onerror,并检查加载的图像(如果您在开始时对该图像有所了解)。
你可能会弄清楚你期望这种情况发生多少次,因为你正在为每一个可能不必要的图像注册某种听众。
答案 4 :(得分:-1)
我可能会迟到,但我也有这种情况,我提出的解决方案是加载时的ajax,然后检查ajax是否失败。为简洁起见,我在这里使用了jQuery。希望它可以帮助别人。
$('#image').on('load',function(e){
var self = this;
$.get($(this).attr('src'))
.then(function(){
// do nothing
},function(){
console.log('do something if it has error');
});
});
答案 5 :(得分:-1)
如果您确定现有图像和404图像之间的尺寸不同,您可以使用该信息进行其他操作。
例如,您希望该节目提供最大的16:9 Youtube缩略图。如果获取的缩略图不存在,Youtube将返回120像素×90像素的“404图像”。因此,让我们获取maxresdefault
缩略图,并将mqdefault
缩略图显示为后备:
<img src="https://img.youtube.com/vi/{id}/maxresdefault.jpg" onload="if (this.naturalWidth === 120) {this.src = this.currentSrc.replace('maxresdefault', 'mqdefault');}">