html

Show fallback message on image load failed AMP

The code will show a fallback message if the src of amp-img is incorrect or the browser failed to load the requested image.

<amp-img src="wrong_image_path.jpg" height="500" width="700" layout="responsive">
    <div fallback style="background-color: #fafafa; display: flex; justify-content: center; align-items: center;">
        Image could not be loaded
    </div>
</amp-img>

Using the code snippet, we will show a message - Image could not be loaded if the image failed to load on the webpage. The message code that we used for this is

<div fallback style="background-color: #fafafa; display: flex; justify-content: center; align-items: center;">
    Image could not be loaded
</div>

Adding a fallback image to the AMP animation element

You can add a fallback image to the AMP animation element, Below is the sample code where we are adding an image placeholder as a fallback for the amp-anim element. It will be shown to the user until the animated element src load.

<amp-anim src="path/to/animated/element/anime_image.gif"
  layout="responsive"
  width="800"
  height="500">
  <amp-img placeholder
    src="path/to/image/static_image.png"
    layout="fill">
  </amp-img>
</amp-anim>

Adding a fallback message to AMP video element

You can add a fallback message on the AMP video element by using the below code.

<amp-video controls
  width="740"
  height="430"
  layout="responsive"
  src="/path/to/video.mp4"
  poster="/path/to/video/poster.png">
  <div fallback>
    <p>Your browser does not support video element</p>
  </div>
</amp-video>

The above code will show a message - "Your browser does not support video element" if the browser failed to load the video from the source.

Adding a fallback image to AMP image element

Sometimes you use webp format images that are supported in chrome browser only and if they failed to load you can load a jpeg format image in the browser that does not support webp image.

<amp-img alt="image alt text"
  width="700"
  height="400"
  layout="responsive"
  src="/path/to/webp/image.webp">
  <amp-img alt="image alt text"
    fallback
    width="700"
    height="400"
    layout="responsive"
    src="/path/to/jpeg/image.jpg"></amp-img>
</amp-img>
Was this helpful?