jqueryimagefunctionattrunbind

image error load placeholder image issue on mobile safari/chrome


I am using the following script to load a placeholder image, if an image src png is not available/error's:

<script type="text/javascript">
jQuery("img").error(function () {
    jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png");
});
</script>

I am loading the above script just before the closing </body> tag.

It works fine on Chrome desktop & shows the placeholder image.

It doesn't work on Safari Desktop or on Mobile phone in Safari/Chrome

Any idea's?


Solution

  • It could be because handler not called if onerror event already fired, you could try instead to capture onerror event, place this script just before </head> tag:

    document.addEventListener('error', function (event) {
         var elm = event.target;
         if (elm.tagName == 'IMG') {
             elm.src = "/images/people_placeholder.png";
         }
     }, true ); // true to capture event
    

    Or try checking for specific properties, you could use just before </body> tag:

    jQuery("img").one('error', function () {
        jQuery(this).attr("src", "/images/people_placeholder.png"); //.unbind("error") is useless here
    }).each(function () {
        if (this.complete && !this.naturalHeight && !this.naturalWidth) {
            $(this).triggerHandler('error');
        }
    });