Skip to content

Commit

Permalink
Add: Auto Sizes for Lazy-loaded Images
Browse files Browse the repository at this point in the history
This adds a new module that will automatically enhance the `sizes` attribute of lazy-loaded images to support the new `auto` syntax.

See: whatwg/html#4654

Fixes: #791.
  • Loading branch information
joemcgill committed Dec 14, 2023
1 parent 0e10d5a commit 9a14b1f
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
71 changes: 71 additions & 0 deletions modules/images/auto-sizes/hooks.php
@@ -0,0 +1,71 @@
<?php
/**
* Hook callbacks used for Auto Sizes for Lazy-loaded Images.
*
* @package performance-lab
* @since n.e.x.t
*/

if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

/**
* Adds auto to the sizes attribute to the image, if applicable.
*
* @since n.e.x.t
*
* @param array $attr Attributes for the image markup.
* @return array The filtered attributes for the image markup.
*/
function performance_lab_auto_sizes_attr( $attr ) {
// Bail early if the image is not lazy-loaded.
if ( ! isset( $attr['loading'] ) || 'lazy' !== $attr['loading'] ) {
return $attr;
}

// Bail early if the image is not responsive.
if ( ! isset( $attr['sizes'] ) ) {
return $attr;
}

// Don't add 'auto' to the sizes attribute if it already exists.
if ( false !== strpos( $attr['sizes'], 'auto,' ) ) {
return $attr;
}

$attr['sizes'] = 'auto, ' . $attr['sizes'];

return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'performance_lab_auto_sizes_attr' );

/**
* Adds auto to the sizes attribute to the image, if applicable.
*
* @since n.e.x.t
*
* @param string $html The HTML image tag markup being filtered.
* @return string The filtered HTML image tag markup.
*/
function performance_lab_auto_sizes_img_tag( $html ) {
// Bail early if the image is not lazy-loaded.
if ( false === strpos( $html, 'loading="lazy"' ) ) {
return $html;
}

// Bail early if the image is not responsive.
if ( false === strpos( $html, 'sizes="' ) ) {
return $html;
}

// Don't double process content images.
if ( false !== strpos( $html, 'sizes="auto,' ) ) {
return $html;
}

$html = str_replace( 'sizes="', 'sizes="auto, ', $html );

return $html;
}
add_filter( 'wp_content_img_tag', 'performance_lab_auto_sizes_img_tag' );
18 changes: 18 additions & 0 deletions modules/images/auto-sizes/load.php
@@ -0,0 +1,18 @@
<?php
/**
* Module Name: Auto Sizes for Lazy-loaded Images.
* Description: Implements auto sizes for lazy loaded images.
* Experimental: Yes
*
* @package performance-lab
* @since n.e.x.t
*/

// Define the constant.
if ( defined( 'IMAGE_AUTO_SIZES' ) ) {
return;
}

define( 'IMAGE_AUTO_SIZES', 'Performance Lab ' . PERFLAB_VERSION );

require_once __DIR__ . '/hooks.php';

0 comments on commit 9a14b1f

Please sign in to comment.