Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<img> onerror with 404 image response

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.

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)" />

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.

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

like image 1000
Brad Avatar asked Feb 26 '15 20:02

Brad


People also ask

What is Onerror in IMG tag?

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image). Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are: onabort.

What is Onerror attribute?

The onerror attribute fires when an error occurs while loading an external file (e.g. a document or an image).


1 Answers

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

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>
like image 176
Patrick Webster Avatar answered Sep 18 '22 12:09

Patrick Webster