< IMG>与404图像响应的错误

问题描述:

我正在从服务器加载图像,当存在404时返回图像。也就是说,如果我加载的图像不存在,服务器将返回404响应,其中包含200x200 PNG后备图像照片不可用就可以了。

I'm loading images from a server which returns images when there is a 404. That is, if the image I'm loading doesn't exist, the server will return a 404 response with a 200x200 PNG fallback image that says "photo not available" on it.

我想检测客户端发生这种情况的时间。我尝试了 onerror 属性:

I would like to detect the times when this happens client-side. I tried the onerror attribute:

<img src="http://example.com/photo.jpg" onerror="console.log(this)" />

此代码仅在服务器的404响应完全没有图像时有效。由于我的404响应确实存在, onerror 事件永远不会被触发。

This code only works when the 404 response from the server has no image at all. Since my 404 response does, the onerror event is never fired.

有没有解决这个问题的方法,简短使用JavaScript预加载图像?

Is there a way around this problem, short of pre-loading images with JavaScript?

(更新,因为@Brad指出了我无知的明显细节。)

(Updated, as @Brad pointed out the obvious details I was ignorant to.)

我偶然发现了这个正确触发onerror():

I stumbled across this which seems to trigger the onerror() properly:

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