Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use onerror() attribute in <amp-img>

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>
like image 244
dom Avatar asked Mar 08 '23 09:03

dom


1 Answers

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:enter image description here

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:enter image description here

See Official Document: Amp Image - Offline Fallback

like image 60
GuRu Avatar answered Mar 16 '23 13:03

GuRu