ampproject / amp-toolbox

A collection of AMP tools making it easier to publish and host AMP pages.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Optimizer: Add OptimizeHeroImages configuration to allow media-less images to be preloaded

westonruter opened this issue · comments

As of #1132, image preloading was turned off for images that lack a media attribute, since otherwise images can accidentally be preloaded which are shown exclusively to mobile to desktop:

if (!heroImage.media) {
// We can only safely preload a hero image if there's a media attribute
// as we can't detect whether it's hidden on certain viewport sizes otherwise.
return;
}

However, there are many cases where a template doesn't actually have viewport-dependent hero images. For them, therefore whether or not a hero image without a media attribute gets preloaded should be dictated by by a configuration option (which defaults to false).

It's also possible that some media-less hero images may be viewport-specific whereas others are shared. Consider a template that has a square logo for mobile but a rectangular logo for desktop, but both mobile and desktop share the same top story image. This case should also be accounted for, however I'm not sure the best way to do so with configuration. The most flexible way to do so would be for the configuration to take a callback that would allow arbitrary logic to be used to determine whether an image can be preloaded. For example, if only the logo is can't be prerendered, and logos have the class names desktop-logo and mobile-logo respectively for desktop and mobile viewports, then this could be configured as follows:

const transformer = new OptimizeHeroImage( {
    maxHeroCount: 6,
    canPreloadCallback: ( heroImage ) => {
        return ! /logo/.test( heroImage.attribs.class );
    }
} );

I realize that transformer configurations up until now may be limited to JSON-primitives, but this seems the most flexible.