Media: Enable lazy-loading of images by automatically adding the new loading="lazy" attribute to image tags on the front-end.

- Introduces `wp_lazy_loading_enabled()`, `wp_filter_content_tags()`, `wp_img_tag_add_loading_attr()`, and `wp_img_tag_add_srcset_and_sizes_attr()` functions.
- Introduces `wp_lazy_loading_enabled`, `wp_img_tag_add_loading_attr`, and `wp_img_tag_add_srcset_and_sizes_attr` filters.

Props flixos90, addyosmani, mor10, swissspidy, pierlo, westonruter, spacedmonkey, mikeschroder, jonoaldersonwp, peterwilsoncc, narwen, jeffpaul, OptimizingMatters, futtta, mukeshpanchal27, azaozz.

Fixes #44427.
Built from https://develop.svn.wordpress.org/trunk@47554


git-svn-id: http://core.svn.wordpress.org/trunk@47329 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Andrew Ozz 2020-04-08 00:55:07 +00:00
parent 195312ead2
commit 0e38f8ed26
5 changed files with 251 additions and 63 deletions

View File

@ -175,13 +175,14 @@ add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_content', 'wp_make_content_images_responsive' );
add_filter( 'the_content', 'wp_filter_content_tags' );
add_filter( 'the_excerpt', 'wptexturize' );
add_filter( 'the_excerpt', 'convert_smilies' );
add_filter( 'the_excerpt', 'convert_chars' );
add_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_excerpt', 'shortcode_unautop' );
add_filter( 'the_excerpt', 'wp_filter_content_tags' );
add_filter( 'get_the_excerpt', 'wp_trim_excerpt', 10, 2 );
add_filter( 'the_post_thumbnail_caption', 'wptexturize' );
@ -207,6 +208,7 @@ add_filter( 'widget_text_content', 'wptexturize' );
add_filter( 'widget_text_content', 'convert_smilies', 20 );
add_filter( 'widget_text_content', 'wpautop' );
add_filter( 'widget_text_content', 'shortcode_unautop' );
add_filter( 'widget_text_content', 'wp_filter_content_tags' );
add_filter( 'widget_text_content', 'do_shortcode', 11 ); // Runs after wpautop(); note that $post global will be null when shortcodes run.
// RSS filters.

View File

@ -2509,11 +2509,11 @@ function is_term( $term, $taxonomy = '', $parent = 0 ) {
* Determines whether the current admin page is generated by a plugin.
*
* Use global $plugin_page and/or get_plugin_page_hookname() hooks.
*
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
*
* @since 1.5.0
* @deprecated 3.1.0
*
@ -3716,11 +3716,11 @@ function get_comments_popup_template() {
/**
* Determines whether the current URL is within the comments popup window.
*
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
*
* @since 1.5.0
* @deprecated 4.5.0
*
@ -3950,3 +3950,21 @@ function wp_ajax_press_this_add_category() {
wp_send_json_error( array( 'errorMessage' => __( 'The Press This plugin is required.' ) ) );
}
}
/**
* Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
*
* @since 4.4.0
* @deprecated 5.5.0
*
* @see wp_image_add_srcset_and_sizes()
*
* @param string $content The raw post content to be filtered.
* @return string Converted content with 'srcset' and 'sizes' attributes added to images.
*/
function wp_make_content_images_responsive( $content ) {
_deprecated_function( __FUNCTION__, '5.5.0', 'wp_filter_content_tags()' );
// This will also add the `loading` attribute to `img` tags, if enabled.
return wp_filter_content_tags( $content );
}

View File

@ -1021,20 +1021,29 @@ function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon
function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
$html = '';
$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
if ( $image ) {
list( $src, $width, $height ) = $image;
$hwstring = image_hwstring( $width, $height );
$size_class = $size;
$attachment = get_post( $attachment_id );
$hwstring = image_hwstring( $width, $height );
$size_class = $size;
if ( is_array( $size_class ) ) {
$size_class = join( 'x', $size_class );
}
$attachment = get_post( $attachment_id );
$default_attr = array(
'src' => $src,
'class' => "attachment-$size_class size-$size_class",
'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
);
// Add `loading` attribute.
if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
$default_attr['loading'] = 'lazy';
}
$attr = wp_parse_args( $attr, $default_attr );
// Generate 'srcset' and 'sizes' if not already present.
@ -1061,18 +1070,21 @@ function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = f
*
* @since 2.8.0
*
* @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
* @param array $attr Array of attribute values for the image markup, keyed by attribute name.
* See wp_get_attachment_image().
* @param WP_Post $attachment Image attachment post.
* @param string|array $size Requested size. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
*/
$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
$attr = array_map( 'esc_attr', $attr );
$html = rtrim( "<img $hwstring" );
foreach ( $attr as $name => $value ) {
$html .= " $name=" . '"' . $value . '"';
}
$html .= ' />';
}
@ -1477,56 +1489,6 @@ function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null,
return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
}
/**
* Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
*
* @since 4.4.0
*
* @see wp_image_add_srcset_and_sizes()
*
* @param string $content The raw post content to be filtered.
* @return string Converted content with 'srcset' and 'sizes' attributes added to images.
*/
function wp_make_content_images_responsive( $content ) {
if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
return $content;
}
$selected_images = array();
$attachment_ids = array();
foreach ( $matches[0] as $image ) {
if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) ) {
$attachment_id = absint( $class_id[1] );
if ( $attachment_id ) {
/*
* If exactly the same image tag is used more than once, overwrite it.
* All identical tags will be replaced later with 'str_replace()'.
*/
$selected_images[ $image ] = $attachment_id;
// Overwrite the ID when the same image is included more than once.
$attachment_ids[ $attachment_id ] = true;
}
}
}
if ( count( $attachment_ids ) > 1 ) {
/*
* Warm the object cache with post and meta information for all found
* images to avoid making individual database calls.
*/
_prime_post_caches( array_keys( $attachment_ids ), false, true );
}
foreach ( $selected_images as $image => $attachment_id ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
$content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
}
return $content;
}
/**
* Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
*
@ -1616,6 +1578,193 @@ function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
return $image;
}
/**
* Determine whether to add the `loading` attribute to the specified tag in the specified context.
*
* @since 5.5.0
*
* @param string $tag_name The tag name.
* @param string $context Additional context, like the current filter name or the function name from where this was called.
* @return bool Whether to add the attribute.
*/
function wp_lazy_loading_enabled( $tag_name, $context ) {
// By default add to all 'img' tags.
// See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
$default = ( 'img' === $tag_name );
/**
* Filters whether to add the `loading` attribute to the specified tag in the specified context.
*
* @since 5.5.0
*
* @param bool $default Default value.
* @param string $tag_name The tag name.
* @param string $context Additional context, like the current filter name or the function name from where this was called.
*/
return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
}
/**
* Filters specific tags in post content and modifies their markup.
*
* This function adds `srcset`, `sizes`, and `loading` attributes to `img` HTML tags.
*
* @since 5.5.0
*
* @see wp_img_tag_add_loading_attr()
* @see wp_img_tag_add_srcset_and_sizes_attr()
*
* @param string $content The HTML content to be filtered.
* @param string $context Optional. Additional context to pass to the filters. Defaults to `current_filter()` when not set.
* @return string Converted content with images modified.
*/
function wp_filter_content_tags( $content, $context = null ) {
if ( null === $context ) {
$context = current_filter();
}
$add_loading_attr = wp_lazy_loading_enabled( 'img', $context );
if ( false === strpos( $content, '<img' ) ) {
return $content;
}
if ( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches ) ) {
return $content;
}
// List of the unique `img` tags found in $content.
$images = array();
foreach ( $matches[0] as $image ) {
if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) ) {
$attachment_id = absint( $class_id[1] );
if ( $attachment_id ) {
// If exactly the same image tag is used more than once, overwrite it.
// All identical tags will be replaced later with 'str_replace()'.
$images[ $image ] = $attachment_id;
continue;
}
}
$images[ $image ] = 0;
}
// Reduce the array to unique attachment IDs.
$attachment_ids = array_unique( array_filter( array_values( $images ) ) );
if ( count( $attachment_ids ) > 1 ) {
/*
* Warm the object cache with post and meta information for all found
* images to avoid making individual database calls.
*/
_prime_post_caches( $attachment_ids, false, true );
}
foreach ( $images as $image => $attachment_id ) {
$filtered_image = $image;
// Add 'srcset' and 'sizes' attributes if applicable.
if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
$filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
}
// Add 'loading' attribute if applicable.
if ( $add_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
$filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
}
if ( $filtered_image !== $image ) {
$content = str_replace( $image, $filtered_image, $content );
}
}
return $content;
}
/**
* Adds `loading` attribute to an `img` HTML tag.
*
* @since 5.5.0
*
* @param string $image The HTML `img` tag where the attribute should be added.
* @param string $context Additional context to pass to the filters.
* @return string Converted `img` tag with `loading` attribute added.
*/
function wp_img_tag_add_loading_attr( $image, $context ) {
/**
* Filters the `loading` attribute value. Default `lazy`.
*
* Returning `false` or an empty string will not add the attribute.
* Returning `true` will add the default value.
*
* @since 5.5.0
*
* @param string $value The `loading` attribute value, defaults to `lazy`.
* @param string $image The HTML `img` tag to be filtered.
* @param string $context Additional context about how the function was called or where the img tag is.
*/
$value = apply_filters( 'wp_img_tag_add_loading_attr', 'lazy', $image, $context );
if ( $value ) {
if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
$value = 'lazy';
}
$quote = null;
// Check if the img tag is valid (has `src` attribute) and get the quote character.
// In almost all cases it will have src and a double quote.
if ( false !== strpos( $image, ' src="' ) ) {
$quote = '"';
} elseif ( preg_match( '/\ssrc\s*=(["\'])/', $image, $matches ) ) {
$quote = $matches[1];
}
if ( $quote ) {
$loading = "loading={$quote}{$value}{$quote}";
return str_replace( '<img', "<img {$loading}", $image );
}
}
return $image;
}
/**
* Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
*
* @since 5.5.0
*
* @param string $image The HTML `img` tag where the attribute should be added.
* @param string $context Additional context to pass to the filters.
* @param int $attachment_id Image attachment ID.
* @return string Converted 'img' element with 'loading' attribute added.
*/
function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
/**
* Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
*
* Returning anything else than `true` will not add the attributes.
*
* @since 5.5.0
*
* @param bool $value The filtered value, defaults to `true`.
* @param string $image The HTML `img` tag where the attribute should be added.
* @param string $context Additional context about how the function was called or where the img tag is.
* @param int $attachment_id The image attachment ID.
*/
$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
if ( true === $add ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
}
return $image;
}
/**
* Adds a 'wp-post-image' class to post thumbnails. Internal use only.
*

View File

@ -2606,6 +2606,8 @@ if ( ! function_exists( 'get_avatar' ) ) :
* Default null.
* @type bool $force_display Whether to always show the avatar - ignores the show_avatars option.
* Default false.
* @type string $loading Value for the `loading` attribute.
* Default null.
* @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
* }
* @return string|false `<img>` tag for the user's avatar. False on failure.
@ -2623,9 +2625,14 @@ if ( ! function_exists( 'get_avatar' ) ) :
'alt' => '',
'class' => null,
'force_display' => false,
'loading' => null,
'extra_attr' => '',
);
if ( wp_lazy_loading_enabled( 'img', 'get_avatar' ) ) {
$defaults['loading'] = 'lazy';
}
if ( empty( $args ) ) {
$args = array();
}
@ -2695,6 +2702,18 @@ if ( ! function_exists( 'get_avatar' ) ) :
}
}
// Add `loading` attribute.
$extra_attr = $args['extra_attr'];
$loading = $args['loading'];
if ( in_array( $loading, array( 'lazy', 'eager' ), true ) && ! preg_match( '/\bloading\s*=/', $extra_attr ) ) {
if ( ! empty( $extra_attr ) ) {
$extra_attr .= ' ';
}
$extra_attr .= "loading='{$loading}'";
}
$avatar = sprintf(
"<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
esc_attr( $args['alt'] ),
@ -2703,7 +2722,7 @@ if ( ! function_exists( 'get_avatar' ) ) :
esc_attr( join( ' ', $class ) ),
(int) $args['height'],
(int) $args['width'],
$args['extra_attr']
$extra_attr
);
/**

View File

@ -13,7 +13,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.5-alpha-47553';
$wp_version = '5.5-alpha-47554';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.