Is there any way to use onerror attribute in <amp-img>
?
It was working good in html.
<img src="../images/some-logo1.jpg" onerror="this.src='../images/no-img.jpg';" class="posting-logo-img">
But amp html will create img tag inside amp-img
<amp-img src="/img/amp.jpg" alt="AMP" class="posting-logo-img" onerror="this.src='../images/no-img.jpg';" >
<noscript>
<img src="/img/amp.jpg" alt="AMP">
</noscript>
</amp-img>
We can't use onerror
attribute in amp-img
but, amp provide Offline Fallback
feature instead of onerror
.
amp-img supports AMP's common attributes, this means you can show a fallback in case the image couldn't be loaded. This is great for adding offline support to your AMPs.
When original image not available or return 404, this gives you text output that you given in fallback div:
<style amp-custom>
amp-img > div[fallback] {
display: flex;
align-items: center;
justify-content: center;
background: #f2f2f2;
border: solid 1px #ccc;
}
</style>
<amp-img src="/img/product-image.jpg" width="300" height="100" layout="responsive" class="m1">
<div fallback>offline</div>
</amp-img>
Output:
Now, if you want show any image (e.g. no-image) instead of text when original image not found then set background image for fallback div
<style amp-custom>
amp-img > div[fallback] {
background:url('/img/does-not-exist.jpg') no-repeat;
}
</style>
<amp-img src="/img/product-image.jpg" width="300" height="100" layout="responsive" class="m1">
<div fallback></div>
</amp-img>
Output:
See Official Document: Amp Image - Offline Fallback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With