How to lazy load amp-img?

Bruce picture Bruce · May 3, 2018 · Viewed 7.4k times · Source

What is the approach for lazy loading images for pages that conform to the Google Accelerated Mobile Pages (AMP) project?

It is my understanding that lazy loading means that the image is loaded to the client sometime after the above-the-fold content is rendered. There appears to be three variants of lazy loading:

  1. view port - image loading is triggered by its proximity to the view port
  2. set delay - image loading is triggered by a timer
  3. manual - image loading is triggered by a client event

All these approaches can be implemented using javascript. However, AMP does not allow for javascript, just custom AMP scripts.

The view port approach is the most desirable, as it minimizes content loading to a minimum. AMP has a custom script that supports the view port approach for starting and stopping videos. However, there does not appear to similar support for amp-img.

The set delay appears to be supported with amp-animation, I think. This seems like a rather complex approach. Further, the delay approach is undesirable as the optimum delay depends on internet bandwidth, which is variable.

The delay approach can also be implemented with PHP. However, PHP is parsed on the server-side. This means that the page would have to reloaded, which entirely defeats the purpose of lazy loading.

It seems that the manual approach is all that remains. The following snippet of code creates two buttons that selectively show or hide an image.

amp-img id='img1' ... hidden

button on="tap.img1.show()"

button on="tap.img1.hide()"

For mobile sites, the show button can be embedded into the above the fold content, so the user triggers it while perusing through the site. However, this seem like a kludge

Does Google AMP effectively limit lazy loading to the manual approach, or is there some other way to accomplish view port or delay lazy loading?

Thank you in advance.

Answer

Malte Ubl picture Malte Ubl · May 9, 2018

All AMP elements always are always lazy loaded. There is currently no way to configure the thresholds for lazy loading (e.g. based on distance from the viewport).