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

Lazy load background images added via inline style attributes #1708

Merged
merged 20 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
6191153
Disable loading of bg images not in initial viewport
ShyamGadde Nov 28, 2024
41fe3c3
Lazy load background images
ShyamGadde Nov 28, 2024
e29cb55
Refactor lazy-loading styles to inline implementation
ShyamGadde Nov 28, 2024
5b8b109
Lazy load bg images only when URL metrics for both mobile and desktop…
ShyamGadde Nov 28, 2024
3a50808
Merge branch 'trunk' into add/lazy-load-bg-images
ShyamGadde Nov 28, 2024
ce351c2
Avoid relying on `has-background` class for lazy-loading background i…
ShyamGadde Nov 29, 2024
66e9404
Simplify conditional check for viewport
ShyamGadde Nov 29, 2024
7943980
Move inline CSS to separate file
ShyamGadde Nov 29, 2024
a21dec4
Update Webpack config to minify CSS files
ShyamGadde Nov 29, 2024
12a268d
Update .gitignore to ignore minified CSS files
ShyamGadde Nov 29, 2024
6608a4e
Fix typo in comment for test case
ShyamGadde Nov 29, 2024
c9eb29f
Improve formatting of inline style tag
ShyamGadde Nov 29, 2024
e466d58
Remove unused variable in test case
ShyamGadde Nov 30, 2024
d02fc27
Add test cases for lazy loading background images
ShyamGadde Nov 30, 2024
d9b3b66
Move image_prioritizer_get_lazy_load_script to helper.php
westonruter Nov 30, 2024
2b75add
Combine script and style addition
westonruter Nov 30, 2024
4d70ad0
Rename previous lazy-load code now to be for video specifically
westonruter Nov 30, 2024
c1491ad
Add missing tests for lazy-load script/style functions
westonruter Nov 30, 2024
8ca87d3
Remove logic made obsolete by #1658
westonruter Nov 30, 2024
4cd8a5e
Update README with new lazy bgimage feature
westonruter Nov 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,30 @@
*/
final class Image_Prioritizer_Background_Image_Styled_Tag_Visitor extends Image_Prioritizer_Tag_Visitor {

/**
* Class name used to indicate a background image which is lazy-loaded.
*
* @since n.e.x.t
* @var string
*/
const LAZY_BG_IMAGE_CLASS_NAME = 'od-lazy-bg-image';

/**
* Whether the lazy-loading styles have been added to the head.
*
* @since n.e.x.t
* @var bool
*/
private $added_lazy_styles = false;

/**
* Whether the lazy-loading script was added to the body.
*
* @since n.e.x.t
* @var bool
*/
private $added_lazy_script = false;

/**
* Visits a tag.
*
Expand Down Expand Up @@ -71,6 +95,57 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {
);
}

$this->lazy_load_bg_images( $context );

return true;
}

/**
* Optimizes an element with a background image based on whether it is displayed in any initial viewport.
*
* @since n.e.x.t
*
* @param OD_Tag_Visitor_Context $context Tag visitor context, with the cursor currently at block with a background image.
*/
private function lazy_load_bg_images( OD_Tag_Visitor_Context $context ): void {
$processor = $context->processor;

// Lazy-loading can only be done once there are URL Metrics collected for both mobile and desktop.
if (
$context->url_metric_group_collection->get_first_group()->count() === 0
||
$context->url_metric_group_collection->get_last_group()->count() === 0
) {
return;
}

$xpath = $processor->get_xpath();

$in_any_initial_viewport = $context->url_metric_group_collection->is_element_positioned_in_any_initial_viewport( $xpath );

// If the element is in the initial viewport, do not lazy load its background image.
if ( true === $in_any_initial_viewport || null === $in_any_initial_viewport ) {
return;
}

$processor->add_class( self::LAZY_BG_IMAGE_CLASS_NAME );

if ( ! $this->added_lazy_styles ) {
$processor->append_head_html(
'<style>
Copy link
Member

Choose a reason for hiding this comment

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

Maybe this should be pulled in from a CSS file like we're doing for the lazy script? In this way we can use the minified version when not in SCRIPT_DEBUG mode.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Currently, the Webpack setup doesn't minify CSS files the same way it handles JavaScript, as the TerserPlugin (used by CopyWebpackPlugin) is specifically for JavaScript minification. I'll explore other approaches to address this.

Copy link
Member

Choose a reason for hiding this comment

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

I guess wp-scripts should have some way of doing this? I don't have a lot of experience with setting this up.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

While wp-scripts does handle CSS minification as part of its default build pipeline when importing CSS in JavaScript, it doesn't offer a direct solution for standalone CSS files like these, especially when the goal is to output them in the same directory as the source files.

I think it would be better to use a minifier like cssnano—which is also used by the postcss-loader in the Webpack configuration provided by wp-scripts—through a Webpack plugin like CssMinimizerPlugin, with identical minimizerOptions as in wp-scripts to ensure consistency with the wp-scripts build process.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done in a21dec4.

@media (scripting: enabled) {
.has-background.od-lazy-bg-image {
Copy link
Member

Choose a reason for hiding this comment

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

Where is this has-background class coming from? I don't think we should depend on that being there as any element that has the inline style attribute with the background image is eligible for this lazy loading.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In Gutenberg, the has-background class is typically added to blocks when a background image or color is applied. However, you're right that this might not be consistent, especially with custom blocks or themes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done in ce351c2.

background-image: none !important;
}
}
</style>'
);
$this->added_lazy_styles = true;
}

if ( ! $this->added_lazy_script ) {
$processor->append_body_html( wp_get_inline_script_tag( image_prioritizer_get_lazy_load_bg_image_script(), array( 'type' => 'module' ) ) );
$this->added_lazy_script = true;
}
}
}
18 changes: 18 additions & 0 deletions plugins/image-prioritizer/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,21 @@ function image_prioritizer_get_asset_path( string $src_path, ?string $min_path =

return $min_path;
}

/**
* Gets the script to lazy-load background images.
*
* Load the background image when it approaches the viewport using an IntersectionObserver.
*
* @since n.e.x.t
*/
function image_prioritizer_get_lazy_load_bg_image_script(): string {
$path = image_prioritizer_get_asset_path( 'lazy-load-bg-image.js' );
$script = file_get_contents( __DIR__ . '/' . $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- It's a local filesystem path not a remote request.

if ( false === $script ) {
return '';
}

return $script;
}
24 changes: 24 additions & 0 deletions plugins/image-prioritizer/lazy-load-bg-image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const lazyBgImageObserver = new IntersectionObserver(
( entries ) => {
for ( const entry of entries ) {
if ( entry.isIntersecting ) {
const bgImageElement = /** @type {HTMLElement} */ entry.target;

bgImageElement.classList.remove( 'od-lazy-bg-image' );

lazyBgImageObserver.unobserve( bgImageElement );
}
}
},
{
rootMargin: '100% 0% 100% 0%',
threshold: 0,
}
);

const bgImageElements = document.querySelectorAll(
'.has-background.od-lazy-bg-image'
);
for ( const bgImageElement of bgImageElements ) {
lazyBgImageObserver.observe( bgImageElement );
}
4 changes: 4 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ const imagePrioritizer = ( env ) => {
from: `${ pluginDir }/lazy-load.js`,
to: `${ pluginDir }/lazy-load.min.js`,
},
{
from: `${ pluginDir }/lazy-load-bg-image.js`,
to: `${ pluginDir }/lazy-load-bg-image.min.js`,
},
],
} ),
new WebpackBar( {
Expand Down
Loading