简体   繁体   中英

Detect failed to load image with javascript

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";
}

为错误事件使用事件处理程序,例如

print("<img src=\"data:image/jpeg;base64," . $base64Img . "\" onerror=\"this.src='ieSafeImg.jpg';\" />");

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.

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM