4

Is it possible to detect when an image doesn't load with JavaScript? I plan on using base64 for images, but browsers such as IE 6 and 7 doesn't support it. So instead of displaying a red x, I'd like to detect such an error, then display a non base64 image. Below is an example of my intentions:

PHP
$base64Img = base64 String;
print("<img src=\"data:image/jpeg; base64, ".$base64Img."\" />");


JavaScript  IE 6
catch img load error{
  errorImg.src = "ieSafeImg.jpg";
}

3 Answers 3

3

Use an event handler for the error event, e.g.

print("<img src=\"data:image/jpeg;base64," . $base64Img . "\" onerror=\"this.src='ieSafeImg.jpg';\" />");
Sign up to request clarification or add additional context in comments.

Comments

0

Image has an onerror event and the onerror event is triggered if an error occurs when loading an image.

<img src="image.gif" onerror="alert('The image could not be loaded.')" />

This is only an example of onerror event. You may use it in your way.

Comments

0

You can set a couple error handlers on the object:

<img onerror="handleIEError()" onabort="handleIEError()" src=\"data:image/jpeg; base64, ".$base64Img."\" />

function handleIEError() {
    this.src = "ieSafeImg.jpg";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.