2

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?

user3544484
  • 761
  • 1
  • 9
  • 17
  • Place it within the `

    ` element so that the handler can be attached before any images attempt to load.

    – Cue Jan 08 '15 at 10:01
  • @Cue But then `jQuery("img")` returns empty object and as `onerror` doesn't bubble, you can delegate it. So OP needs to capture it instead or maybe check for all images specific property – A. Wolff Jan 08 '15 at 10:02
  • @A.Wolff yes that's correct, sorry I overlooked the delegation. With jQuery you can do `$(document).on('error', 'img', function () {});` – Cue Jan 08 '15 at 10:05
  • 1
    @Cue No, you cannot delegate `onerror` event **EDIT:** Oops sorry i see in my previous comment, it should be ***cannot delegate*** not ***can delegate*** – A. Wolff Jan 08 '15 at 10:11
  • @A.Wolff needs to be attached directly. I stand corrected. – Cue Jan 08 '15 at 10:26

3 Answers3

5

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');
    }
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

Try This one

I found this Here Link

function imgError(image) {
image.onerror = "";
image.src = "/images/people_placeholder.gif";
return true;
}

HTML:

<img src="image.png" onerror="imgError(this);"/>
Community
  • 1
  • 1
Arunkumar
  • 5,150
  • 4
  • 28
  • 40
0
<img src="URL_OF_IMAGE" alt="image info" onerror="this.src='DEFAULT_IMG_URL'"/>

check docs

or create Global Function to solve this issue

Praveen Patel
  • 199
  • 1
  • 8