Make WordPress Core

11/09/2021 12:34:17 AM (3 years ago)

Media: Refine the heuristics to exclude certain images and iframes from being lazy-loaded to improve performance.

This changeset implements the refined lazy-loading behavior outlined in in order to improve the Largest Contentful Paint metric, which can see a regression from images or iframes above the fold being lazy-loaded. Adjusting this so far has been possible for developers via filters and still is, however this enhancement brings a more accurate behavior out of the box for the majority of themes.

Specifically, this changeset skips the very first "content image or iframe" on the page from being lazy-loaded. "Content image or iframe" denotes any image or iframe that is found within content of any post in the current main query loop as well as any featured image of such a post. This applies both to "singular" as well as "archive" content: On a "singular" page the first image/iframe of the post is not lazy-loaded, while on an "archive" page the first image/iframe of the _first_ post in the query is not lazy-loaded.

This approach refines the lazy-loading behavior correctly for the majority of themes, which use a single-column layout for post content. For themes with multi-column layouts, a new wp_omit_loading_attr_threshold filter can be used to change how many of the first images/iframes are being skipped from lazy-loaded (default is 1). For example, a theme using a three-column grid of latest posts for archives could use the filter to override the threshold to 3 on archive pages, so that the first three content images/iframes would not be lazy-loaded.

Props adamsilverstein, azaozz, flixos90, hellofromtonya, jonoaldersonwp, mte90, rviscomi, tweetythierry, westonruter.
Fixes #53675. See #50425.

1 edited


  • trunk/src/wp-includes/post-thumbnail-template.php

    r52028 r52065  
    187187        }
     189        // Get the 'loading' attribute value to use as default, taking precedence over the default from
     190        // `wp_get_attachment_image()`.
     191        $loading = wp_get_loading_attr_default( 'the_post_thumbnail' );
     193        // Add the default to the given attributes unless they already include a 'loading' directive.
     194        if ( empty( $attr ) ) {
     195            $attr = array( 'loading' => $loading );
     196        } elseif ( is_array( $attr ) && ! array_key_exists( 'loading', $attr ) ) {
     197            $attr['loading'] = $loading;
     198        } elseif ( is_string( $attr ) && ! preg_match( '/(^|&)loading=', $attr ) ) {
     199            $attr .= '&loading=' . $loading;
     200        }
    189202        $html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
Note: See TracChangeset for help on using the changeset viewer.