Skip to content

Optimization Detective: Implement lazy-loading of background images #1035

@westonruter

Description

@westonruter

Feature Description

At the WordCamp Asia Contributor Day, @shilo-ey shared a very interesting thing that Elementor is doing to optimize the loading of background images by lazy-loading them. Background images cannot be lazy-loaded using loading=lazy like regular images can since they are CSS and not img elements. So Elementor is using a clever approach to force all background images to be hidden after the first N with a style rule. Then it uses IntersectionObserver to remove the style rule once scrolling.

https://github.com/elementor/elementor/blob/498d48e8fed6cb8db2b0b3d3835cf1e44efbcbb8/modules/lazyload/module.php#L37-L97

This could be done with Optimization Detective as well, but in a more accurate way since it wouldn't have to assume to not lazy-load the first N images and it can instead use the elements in the URL metrics to know which background images are actually in the initial viewport, and only exclude them from lazy-loading.

See also WordPress/gutenberg#59113

When JavaScript is turned off, the lazy-loading of the background image should ideally be disabled. This can be achieved by wrapping the CSS rules to disable the background images outside the initial viewport with the scripting media query:

@media (scripting: enabled) {
   /*...*/
}

Metadata

Metadata

Assignees

Labels

Needs DevAnything that requires development (e.g. a pull request)[Plugin] Optimization DetectiveIssues for the Optimization Detective plugin[Type] EnhancementA suggestion for improvement of an existing feature

Projects

Status

Done 😃

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions