我正在从服务器加载图像,该服务器在存在404时返回图像。也就是说,如果我正在加载的图像不存在,则服务器将返回404响应,并显示200x200 PNG后备图像,显示“可用”。
我想检测客户端发生这种情况的时间。我尝试了onerror
属性:
<img src="http://example.com/photo.jpg" onerror="console.log(this)" />
仅当来自服务器的404响应完全没有图像时,此代码才有效。由于我的404响应确实存在,因此永远不会触发
onerror
事件。是否可以解决此问题,而无需使用JavaScript预加载图像?
最佳答案
(已更新,正如@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>