Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prioritize loading poster image of video LCP elements #1498

Merged
merged 10 commits into from
Oct 15, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -40,28 +40,14 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {

$xpath = $processor->get_xpath();

/**
* Gets attribute value.
*
* @param string $attribute_name Attribute name.
* @return string|true|null Normalized attribute value.
*/
$get_attribute_value = static function ( string $attribute_name ) use ( $processor ) {
$value = $processor->get_attribute( $attribute_name );
if ( is_string( $value ) ) {
$value = strtolower( trim( $value, " \t\f\r\n" ) );
}
return $value;
};

/*
* When the same LCP element is common/shared among all viewport groups, make sure that the element has
* fetchpriority=high, even though it won't really be needed because a preload link with fetchpriority=high
* will also be added. Additionally, ensure that this common LCP element is never lazy-loaded.
*/
$common_lcp_element = $context->url_metric_group_collection->get_common_lcp_element();
if ( ! is_null( $common_lcp_element ) && $xpath === $common_lcp_element['xpath'] ) {
if ( 'high' === $get_attribute_value( 'fetchpriority' ) ) {
if ( 'high' === $this->get_attribute_value( $processor, 'fetchpriority' ) ) {
$processor->set_meta_attribute( 'fetchpriority-already-added', true );
} else {
$processor->set_attribute( 'fetchpriority', 'high' );
Expand Down Expand Up @@ -92,7 +78,7 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {
} else {
// Otherwise, make sure visible elements omit the loading attribute, and hidden elements include loading=lazy.
$is_visible = $element_max_intersection_ratio > 0.0;
$loading = $get_attribute_value( 'loading' );
$loading = $this->get_attribute_value( $processor, 'loading' );
if ( $is_visible && 'lazy' === $loading ) {
$processor->remove_attribute( 'loading' );
} elseif ( ! $is_visible && 'lazy' !== $loading ) {
Expand All @@ -104,7 +90,7 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {
// Ensure that sizes=auto is set properly.
$sizes = $processor->get_attribute( 'sizes' );
if ( is_string( $sizes ) ) {
$is_lazy = 'lazy' === $get_attribute_value( 'loading' );
$is_lazy = 'lazy' === $this->get_attribute_value( $processor, 'loading' );
$has_auto = $this->sizes_attribute_includes_valid_auto( $sizes );

if ( $is_lazy && ! $has_auto ) {
Expand Down Expand Up @@ -138,7 +124,7 @@ static function ( string $value ): bool {
)
);

$crossorigin = $get_attribute_value( 'crossorigin' );
$crossorigin = $this->get_attribute_value( $processor, 'crossorigin' );
if ( null !== $crossorigin ) {
$link_attributes['crossorigin'] = 'use-credentials' === $crossorigin ? 'use-credentials' : 'anonymous';
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
/**
* Tag visitor that optimizes image tags.
*
* @phpstan-type NormalizedAttributeNames 'fetchpriority'|'loading'|'crossorigin'
*
* @since 0.1.0
* @access private
*/
Expand All @@ -36,4 +38,24 @@ abstract public function __invoke( OD_Tag_Visitor_Context $context ): bool;
protected function is_data_url( string $url ): bool {
return str_starts_with( strtolower( $url ), 'data:' );
}

/**
* Gets attribute value for select attributes.
*
* @since n.e.x.t
* @todo Move this into the OD_HTML_Tag_Processor/OD_HTML_Processor class eventually.
*
* @phpstan-param NormalizedAttributeNames $attribute_name
*
* @param OD_HTML_Tag_Processor $processor Processor.
* @param string $attribute_name Attribute name.
* @return string|true|null Normalized attribute value.
*/
protected function get_attribute_value( OD_HTML_Tag_Processor $processor, string $attribute_name ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to move this eventually into OD_HTML_Tag_Processor/OD_HTML_Processor. Also @dmsnell has suggested this could eventually be part of the core class as well, as most HTML attributes have their own dedicated logic to get back a normalized value.

$value = $processor->get_attribute( $attribute_name );
if ( is_string( $value ) ) {
$value = strtolower( trim( $value, " \t\f\r\n" ) );
}
return $value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php
/**
* Tag visitor that optimizes VIDEO tags:
* - Adds preload links for poster images if in a breakpoint group's LCP.
*
* @package image-prioritizer
*
* @since n.e.x.t
*/

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

/**
* Image Prioritizer: Image_Prioritizer_Video_Tag_Visitor class
*
* @since n.e.x.t
*
* @access private
*/
final class Image_Prioritizer_Video_Tag_Visitor extends Image_Prioritizer_Tag_Visitor {

/**
* Visits a tag.
*
* @param OD_Tag_Visitor_Context $context Tag visitor context.
*
* @return bool Whether the tag should be tracked in URL metrics.
*/
public function __invoke( OD_Tag_Visitor_Context $context ): bool {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@westonruter I suppose this is where I would add the logic for #1575?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes exactly!

$processor = $context->processor;
if ( 'VIDEO' !== $processor->get_tag() ) {
return false;
}

// Skip empty poster attributes and data: URLs.
$poster = trim( (string) $processor->get_attribute( 'poster' ) );
if ( '' === $poster || $this->is_data_url( $poster ) ) {
return false;
}

$xpath = $processor->get_xpath();

// TODO: If $context->url_metric_group_collection->get_element_max_intersection_ratio( $xpath ) is 0.0, then the video is not in any initial viewport and the VIDEO tag could get the preload=none attribute added.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking out loud for a future enhancement:

autoplay takes precedence over preload. Since we here know that the video is not in the initial viewport, we could remove autoplay in favor of an IntersectionObserver-based implementation that only autoplays the video when actually visible.

Thoughts? Worth creating an issue for it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, interesting idea. Yes, I think that warrants an issue.

Related to #1035 which involves IntersectionObserver to lazy-load background images.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: #1590


// If this element is the LCP (for a breakpoint group), add a preload link for it.
foreach ( $context->url_metric_group_collection->get_groups_by_lcp_element( $xpath ) as $group ) {
$link_attributes = array(
'rel' => 'preload',
'fetchpriority' => 'high',
'as' => 'image',
'href' => $poster,
'media' => 'screen',
);

$crossorigin = $this->get_attribute_value( $processor, 'crossorigin' );
if ( null !== $crossorigin ) {
$link_attributes['crossorigin'] = 'use-credentials' === $crossorigin ? 'use-credentials' : 'anonymous';
}

$context->link_collection->add_link(
$link_attributes,
$group->get_minimum_viewport_width(),
$group->get_maximum_viewport_width()
);
}

return true;
}
}
10 changes: 7 additions & 3 deletions plugins/image-prioritizer/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ static function (): void {
require_once __DIR__ . '/class-image-prioritizer-tag-visitor.php';
require_once __DIR__ . '/class-image-prioritizer-img-tag-visitor.php';
require_once __DIR__ . '/class-image-prioritizer-background-image-styled-tag-visitor.php';
require_once __DIR__ . '/class-image-prioritizer-video-tag-visitor.php';

add_action( 'wp_head', 'image_prioritizer_render_generator_meta_tag' );
add_action( 'od_register_tag_visitors', 'image_prioritizer_register_tag_visitors' );
Expand All @@ -58,7 +59,7 @@ function image_prioritizer_render_generator_meta_tag(): void {
}

/**
* Registers tag visitors for images.
* Registers tag visitors.
*
* @since 0.1.0
*
Expand All @@ -67,8 +68,11 @@ function image_prioritizer_render_generator_meta_tag(): void {
function image_prioritizer_register_tag_visitors( OD_Tag_Visitor_Registry $registry ): void {
// Note: The class is invocable (it has an __invoke() method).
$img_visitor = new Image_Prioritizer_Img_Tag_Visitor();
$registry->register( 'img-tags', $img_visitor );
$registry->register( 'image-prioritizer/img', $img_visitor );

$bg_image_visitor = new Image_Prioritizer_Background_Image_Styled_Tag_Visitor();
$registry->register( 'bg-image-tags', $bg_image_visitor );
$registry->register( 'image-prioritizer/background-image', $bg_image_visitor );

$video_visitor = new Image_Prioritizer_Video_Tag_Visitor();
$registry->register( 'image-prioritizer/video', $video_visitor );
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php
return array(
'set_up' => static function ( Test_Image_Prioritizer_Helper $test_case ): void {
$breakpoint_max_widths = array( 480, 600, 782 );

add_filter(
'od_breakpoint_max_widths',
static function () use ( $breakpoint_max_widths ) {
return $breakpoint_max_widths;
}
);

foreach ( array_merge( $breakpoint_max_widths, array( 1000 ) ) as $viewport_width ) {
OD_URL_Metrics_Post_Type::store_url_metric(
od_get_url_metrics_slug( od_get_normalized_query_vars() ),
$test_case->get_sample_url_metric(
array(
'viewport_width' => $viewport_width,
'elements' => array(
array(
'isLCP' => true,
'xpath' => '/*[1][self::HTML]/*[2][self::BODY]/*[1][self::VIDEO]',
),
),
)
)
);
}
},
'buffer' => '
<html lang="en">
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<video class="desktop" poster="https://example.com/poster.jpg" width="1200" height="500" src="https://example.com/header.mp4"></video>
</body>
</html>
',
'expected' => '
<html lang="en">
<head>
<meta charset="utf-8">
<title>...</title>
<link data-od-added-tag rel="preload" fetchpriority="high" as="image" href="https://example.com/poster.jpg" media="screen">
</head>
<body>
<video data-od-xpath="/*[1][self::HTML]/*[2][self::BODY]/*[1][self::VIDEO]" class="desktop" poster="https://example.com/poster.jpg" width="1200" height="500" src="https://example.com/header.mp4"></video>
<script type="module">/* import detect ... */</script>
</body>
</html>
',
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php
return array(
'set_up' => static function ( Test_Image_Prioritizer_Helper $test_case ): void {
$breakpoint_max_widths = array( 480, 600, 782 );

add_filter(
'od_breakpoint_max_widths',
static function () use ( $breakpoint_max_widths ) {
return $breakpoint_max_widths;
}
);

foreach ( $breakpoint_max_widths as $non_desktop_viewport_width ) {
$elements = array(
array(
'isLCP' => true,
'xpath' => '/*[1][self::HTML]/*[2][self::BODY]/*[1][self::IMG]',
),
array(
'isLCP' => false,
'xpath' => '/*[1][self::HTML]/*[2][self::BODY]/*[2][self::VIDEO]',
),
);
OD_URL_Metrics_Post_Type::store_url_metric(
od_get_url_metrics_slug( od_get_normalized_query_vars() ),
$test_case->get_sample_url_metric(
array(
'viewport_width' => $non_desktop_viewport_width,
'elements' => $elements,
)
)
);
}

OD_URL_Metrics_Post_Type::store_url_metric(
od_get_url_metrics_slug( od_get_normalized_query_vars() ),
$test_case->get_sample_url_metric(
array(
'viewport_width' => 1000,
'elements' => array(
array(
'isLCP' => false,
'xpath' => '/*[1][self::HTML]/*[2][self::BODY]/*[1][self::IMG]',
),
array(
'isLCP' => true,
'xpath' => '/*[1][self::HTML]/*[2][self::BODY]/*[2][self::VIDEO]',
),
),
)
)
);
},
'buffer' => '
<html lang="en">
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<img class="mobile" src="https://example.com/mobile-header.jpg" alt="Mobile Logo" width="800" height="600" crossorigin>
<video class="desktop" poster="https://example.com/poster.jpg" width="1200" height="500" crossorigin>
<source src="https://example.com/header.webm" type="video/webm">
<source src="https://example.com/header.mp4" type="video/mp4">
</video>
</body>
</html>
',
'expected' => '
<html lang="en">
<head>
<meta charset="utf-8">
<title>...</title>
<link data-od-added-tag rel="preload" fetchpriority="high" as="image" href="https://example.com/mobile-header.jpg" crossorigin="anonymous" media="screen and (max-width: 782px)">
<link data-od-added-tag rel="preload" fetchpriority="high" as="image" href="https://example.com/poster.jpg" media="screen and (min-width: 783px)" crossorigin="anonymous">
</head>
<body>
<img data-od-xpath="/*[1][self::HTML]/*[2][self::BODY]/*[1][self::IMG]" class="mobile" src="https://example.com/mobile-header.jpg" alt="Mobile Logo" width="800" height="600" crossorigin>
<video data-od-xpath="/*[1][self::HTML]/*[2][self::BODY]/*[2][self::VIDEO]" class="desktop" poster="https://example.com/poster.jpg" width="1200" height="500" crossorigin>
<source src="https://example.com/header.webm" type="video/webm">
<source src="https://example.com/header.mp4" type="video/mp4">
</video>
<script type="module">/* import detect ... */</script>
</body>
</html>
',
);
Loading
Loading