4

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>
Sanchit Gupta
  • 3,148
  • 2
  • 28
  • 36
dom
  • 325
  • 2
  • 15
  • 1
    No. From the docs: `Attribute names starting with on (such as onclick or onmouseover) are disallowed in AMP HTML`. https://www.ampproject.org/docs/reference/spec#html-attributes. To be honest, this is a good thing. `on*` event attributes are very outdated anyway and should not be used. Hook an unobtrusive event handler to the element instead - presumably this renders out a standard `` element? – Rory McCrossan Aug 10 '17 at 07:34

1 Answers1

7

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

GuRu
  • 1,880
  • 3
  • 23
  • 32