Lazy-loading images in 5.5

In WordPress 5.5, images will be lazy-loaded by default, using the native HTML loading attribute which became a web standard earlier in 2020. This will drastically save bandwidth on both servers as well as user agents across sites where images further down the page used to be loaded right away, even in the case the user might never scroll towards them.

By default, WordPress will add loading="lazy" to all img tags that have width and height attributes present. Technically this is handled on page output, similar to how responsive images are facilitated in WordPress by adding srcset and sizes attributes. To improve server-side performance of the two features, a new wp_filter_content_tags() function has been introduced so that img tags only need to be parsed once while then deferring the modifications to more specific functions related to the feature.

See #44427 for the overarching TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker..

Reduced layout shifting as a prerequisite

A common user experience problem in modern website is so-called layout shifting, often caused by slow-loading media resources like images: By default, only after an image is loaded, the browser can layout the page correctly, which results in the content e.g. below the image to shift. This issue can be easily resolved by providing width and height attributes on img tags, as the browser will use them to determine the aspect ratio of the image so that it can infer the page layout ahead of actually loading the image.

While this is already a major problem without lazy-loading images, with lazy-loading it becomes more relevant. Therefore WordPress will only add loading="lazy" to img tags which have both dimension attributes present. At the same time, resolving the underlying issue is just as important to reduce layout shifting in general, which is why with version 5.5 WordPress will start back-filling width and height attributes on img tags when they are not already present. To do that, it reuses the established logic already in place for determining srcset and sizes attributes. Like with those attributes, width and height can only be determined if an image is for a WordPress attachment and if the img tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) includes the relevant wp-image-$id class.

WordPress has mostly been following this best practice, and work is being done to ensure all images in the editor will have width and height. Back-filling these attributes should not have any implications on themes, as long as a theme’s CSSCSS Cascading Style Sheets. works appropriately with classic editor content., which is expected: If an image’s width or height is modified via CSS, the respective other attribute should be set to auto, to avoid the image from being stretched.

See #50367 for further background information on this change.

Customizing lazy-loading

By default, WordPress will add a loading="lazy" attribute to the following images:

  • images within post content (the_content)
  • images within post excerpts (the_excerpt)
  • images within text widgets (widget_text_content)
  • avatarAvatar An avatar is an image or illustration that specifically refers to a character that represents an online user. It’s usually a square box that appears next to the user’s name. images (get_avatar)
  • template images using wp_get_attachment_image() (wp_get_attachment_image)

Developers can customize this behavior through various filters, the most foundational one being wp_lazy_loading_enabled, which receives the following parameters:

  • $default: The boolean default of true to filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output..
  • $tag_name: An HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. tag name. While per current WordPress behavior this will always be img, it should be noted that the loading attribute is a generic attribute and may be expanded to support further elements, e.g. iframes, in the future.
  • $context: A context string as additional parameters, indicating where the image technically comes from, usually a WordPress hook name. Based on how WordPress itself uses lazy-loading, the context can be one of the five values in parentheses in the list above.

For example, if you would like to turn off lazy-loading by default for template images, you could use the following code snippet:

function disable_template_image_lazy_loading( $default, $tag_name, $context ) {
	if ( 'img' === $tag_name && 'wp_get_attachment_image' === $context ) {
		return false;
	}
	return $default;
}
add_filter(
	'wp_lazy_loading_enabled',
	'disable_template_image_lazy_loading',
	10,
	3
);

In order to modify the loading attribute for very specific images, there are two different approaches, depending on the type of images:

For images that appear within a content blob (e.g. the_content, the_excerpt, widget_text_content), another new filter wp_img_tag_add_loading_attr can be used, which receives the following parameters:

  • $value: The loading attribute value, either “lazy” (default), “eager”, or false. If you want to disable lazy-loading for an image, it is strongly recommended to specify false so that the attribute is omitted altogether.
  • $image: The entire image HTML tag with its attributes.
  • $context: The context, similar as described for the other filter above.

For example, if you would like to disable lazy-loading for a specific attachment image with ID 42 in size “large” within post content, you could use the following code snippet:

function skip_loading_lazy_image_42_large( $value, $image, $context ) {
	if ( 'the_content' === $context ) {
		$image_url = wp_get_attachment_image_url( 42, 'large' );
		if ( false !== strpos( $image, ' src="' . $image_url . '"' ) {
			return false;
		}
	}
	return $value;
}
add_filter(
	'wp_img_tag_add_loading_attr',
	'skip_loading_lazy_image_42_large',
	10,
	3
);

For images which are output via wp_get_attachment_image(), the attribute can simply be controlled through the function’s $attr parameter, which can be the same possibles values like the $value parameter for the above filter. In order to not lazy-load an image, an attribute value of false should be specified, which will result in the attribute being omitted. For example:

echo wp_get_attachment_image(
	42,
	'large',
	false,
	array( 'loading' => false ),
);

Theme developers are recommended to granularly handle loading attributes for images anytime they rely on wp_get_attachment_image() or another function based on it (such as the_post_thumbnail() or get_custom_logo()), depending on where they are used within templates. For example, if an image is placed within the header.php template and is very likely to be in the initial viewport, it is advisable to skip the loading attribute for that image.

Images that are marked as candidates for lazy-loading require the browser to resolve where the image is positioned on the page, which relies on the IntersectionObserver to be available and thus as of today slightly delays their fetching. Experiments using Chrome for Android have shown that the impact of such loading=”lazy” images in the initial viewport on the Largest Contentful Paint metric is fairly small, with a regressionregression A software bug that breaks or degrades something that previously worked. Regressions are often treated as critical bugs or blockers. Recent regressions may be given higher priorities. A "3.6 regression" would be a bug in 3.6 that worked as intended in 3.5. of <1% at the 75th and 99th percentiles compared to non lazy-loaded images – yet it is a consideration to make where theme developers can apply some fine tuning for even better user experience.

See #50425 for further background information on this change.

Browser compatibility

The loading attribute is widely supported by modern browsers, with an increasing trend: For example, while Safari support is not yet available at the time of publication, the feature is being worked on there as well and has already been merged into the underlying WebKit engine.

Yet, even browsers that currently do not support the loading attribute will not see any negative consequences from WordPress providing the attribute on images, since the native lazy-loading mechanism is implemented as a fully progressive enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature.: For those browsers the attribute will simply be ignored. This also means that whenever a browser implements support for the feature, its users will get the benefits right away when they browse WordPress-powered sites.

Props @azaozz for helping with this post.

#5-5, #dev-notes, #feature-lazyloading

Lazy-loading of images is in core

As planned, the patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. for adding loading attribute to img tags is now committed to coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. (see #44427).

Based on preliminary testing there seem to be no conflicts with most plugins that implement lazy-loading for images. Nevertheless the authors of these plugins are strongly advised to test them in trunktrunk A directory in Subversion containing the latest development code in preparation for the next major release cycle. If you are running "trunk", then you are on the latest revision. (WordPress 5.5-alpha) and confirm their plugins work as expected.

It would also be very beneficial to the users if the plugins that implement lazy-loading are updated to utilize the new Core functionality and filters, and to use the new loading HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. attribute. Please see https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading and https://html.spec.whatwg.org/multipage/urls-and-fetching.html#lazy-loading-attributes.

A dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include: a description of the change; the decision that led to this change a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase. with more details on the implementation and how to customize the behavior will be published closer to the WordPress 5.5 release.

#feature-lazyloading

Dev Chat summary – March 25, 2020

@francina facilitated the chat on this agenda.

Full meeting transcript on Slack

This devchat marked week 11 of the 5.4 release cycle.

Announcements

WordPress 5.4 Release Candidate 4 was released on Tuesday March 24, 2020 and everything went smoothly.

@audrasjb shared an update on WP Auto-updates Feature PluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins.: it was moved from his personal GitHubGitHub GitHub is a website that offers online implementation of git repositories that can can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ account to WordPress/wp-autoupdates which is the new official GitHub repository of this project. The #core-auto-updates team will try to ship version 0.4 before WP 5.4 is released. This new version aims to handle auto-updates for themes.

@afragen asked for a review of some Trac tickets which are all associated with Theme compatibility checks and will likely have interaction with the auto-updates feature. The idea is to ship them early in WordPress 5.5.

@whyisjake pointed out that he really like the work that is going on in #core-auto-updates SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel and think that trying to land in the next few releases would be excellent. Related, He’d love to see #core-passwords (two-factors authentification – 2FA) land in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. too. In his opinion, the pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party is so mature at this point that having it left out almost seems like an omission. @whyisjake is going to work on a merge proposal.

@clorith raised that it would be necessary to make sure that the 2FA proposal also highlights the concerns with how to address users locking them selves out (which was the major holdback previously).

@azaozz announced that the patch for image lazy-loading attribute is ready for testing.

Upcoming Releases

The current major is 5.4, scheduled to go out on March 31st 2020; please keep testing for all the bugs!

There are two ways do it:

Trunktrunk A directory in Subversion containing the latest development code in preparation for the next major release cycle. If you are running "trunk", then you are on the latest revision. has been branched to 5.5 on the beginning of March. That means 5.5 is officially in Alpha.

@francina announced that work for 5.6 –which is going to be an all-women release– has kicked off with an initial round of messages going out to the women that expressed interest. @angelasjin @francina and Chloé Bringmann are contacting them to hear if they are still interested, what skills they have and what expectations.

Components Check-in

@francina shared a proposal to change the Components Check-in. This is always done towards the end of the chat and feels rushed. There is never really time to dig into the topics they might bring up. Francesca shared two ideas:

  1. Schedule a weekly post where they can leave their status update, like the one for Community deputies.
  2. Adopt a Slack Bot that once a week will ask the maintainers for a status update: maybe in a new component-maintainers Slack channel. Core is getting very busy with TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. and Travis bots, and RSS.

@johnbillion added that trying a weekly post could be a good idea. Maybe every Tuesday so it’s ready for the dev chat on Wednesdays in case anything comes up.

@francina proposed to talk to #meta to set this up and test drive it for 8 weeks.

Open floor

@isabel_brison proposed to create a set of guidelines for Internet Explorer support. The CSSCSS Cascading Style Sheets. team kind of decided on starting to deprecate it, and “graceful degradation” seems a good way to go forward, meaning Core can use unsupported technology to make non-essential enhancements. Isabel wants to agree on what’s “essential” here, and created a Trac ticketticket Created for both bug reports and feature development on the bug tracker. to start the discussion: #49696

@paaljoachim suggested to puntpunt Contributors sometimes use the verb "punt" when talking about a ticket. This means it is being pushed out to a future release. This typically occurs for lower priority tickets near the end of the release cycle that don't "make the cut." In this is colloquial usage of the word, it means to delay or equivocate. (It also describes a play in American football where a team essentially passes up on an opportunity, hoping to put themselves in a better position later to try again.) default full screen mode to 5.5 as there is a pull request on Gutenberg project GitHub repository to provide an alternative approach.

@audrasjb pointed out that the proposal in this pull request would be a way better than the current implementation.

@whyisjake added that this is not a realistic change for WP 5.4, it’s a proof of concept, and not a fully tested feature.

@francina confirmed that @matt took the decision to ship WordPress 5.4 with this feature. Matt also commented in the Accessibility Team statement post.

@joyously stated it’s hard to contribute when concerns are ignored. @chanthaboune answered she can understand how they can feel ignored. A lot of that research gets done solo, and it’s often hard to remember to recap your own research. For full site editing to be a reality by the end of the year, the work can start bringing incremental changes. This change is feeling very jarring, but there is more worry about not have any mid-point between here and Full Site Editing.

@peterwilsoncc, @clorith and @audrasjb agreed that since RC4 was released, it’s not realistic to revert this change. The discussion can continue in a post-mortem post on Make/Core.

#5-4, #5-5, #5-6, #dev-chat, #feature-autoupdates, #feature-lazyloading, #two-factor

Lazy-Loading Update

Since lazy-loading images via the native loading attribute was proposed for addition to WordPress core, there have been quite a few updates. With the WordPress 5.4 release cycle entering betaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. almost two weeks ago, there was too little time for testing the feature plugin and creating a proper coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing.. The feature is now aimed at being released as part of WordPress 5.5, to be merged early in the release cycle to get further testing while fully integrated with the platform. This post is a follow-up to the original announcement, providing information about the latest updates.

Standardization of the loading attribute

The WHATWG spec pull-request for adding the loading attribute to img elements with possible values “eager” and “lazy” was recently merged, so it is now part of the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. Living Standard (see general paragraph about lazy loading attributes and more specific information about the img loading attribute). This was a requirement for WordPress to ship with support for the feature. While it was unclear whether this was going to happen in time for the WordPress 5.4 release (which it now has), the 5.5 timeline certainly works for it, as now the feature can be merged way ahead of the initial beta.

Browser support

At the time of this publication, Chrome (76+), Edge (79+) and Opera (64+) already support the loading attribute. Firefox support was merged recently, and is intended to land in version 75. WebKit support is actively being worked on, so seeing the feature land in Safari is also on the horizon. We will monitor how browser vendors are adopting the standard, but with recent developments it looks promising. All major browsers will support the loading attribute by the time WordPress 5.5 is released (currently 2020/08/11). Please refer to caniuse.com for current updates.

State of the feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins.

The feature plugin for lazy-loading images in WordPress core (GitHub repository) is in a good state to be used already. The exact implementation is undergoing some changes, mainly focused on optimizing the mechanism to add the loading attribute to images in post content for performance by combining it with the existing regular expression in core that adds srcset and sizes attributes. These changes will likely affect the new APIs outlined in the original post, and a dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include: a description of the change; the decision that led to this change a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase. about the definite state will be published closer to the WordPress 5.5 release.

The pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party is ready to be widely tested. It has already undergone some testing, but we are looking for more testers! We will also like to receive any type of feedback on the implementation.

#feature-lazyloading

Lazy-Loading Images in WordPress Core

Lazy-loading images has been a commonly used mechanism to significantly improve pageload performance for several years. For the WordPress ecosystem alone, there are a myriad of plugins that enable lazy-loading.

While historically lazy-loading images has required a custom JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/.-based approach, there is now a native web solution which relies solely on the presence of a new loading attribute on img tags and provides a standardized user experience without content shifting. The HTML specification for the loading attribute is near completion and is already supported by several browsers, including Chrome and Edge.

Enabling lazy-loading for images in WordPress content was first proposed nearly two years ago, however the JavaScript implementation at the time would potentially have introduced many edge cases and failures. Using the new loading attribute removes these concerns. This post describes the suggested solution.

Performance Impact

According to HTTPArchive, images are the most requested asset type for most websites and usually take up more bandwidth than any other resource. At the 90th percentile, sites send about 4.7 MB of images on desktop and mobile.

Native lazy-loading for the web, web.dev

Without lazy-loading, all images on a web page are loaded immediately. This can significantly harm performance, especially on pages that contain many images. If several of these images are “below the fold”, i.e. the part of the page that the user does not immediately see, loading those images right away is unnecessary and potentially even wasteful of networknetwork (versus site, blog) resources: If the user never scrolls towards those images, they would have been loaded regardless.

Since lazy-loading has become a must-have performance improvement, the new loading attribute specification aims to standardize the behavior and make it even faster, integrated in the web platform.

With WordPress enabling native lazy-loading by default, it would significantly impact performance and user experience for millions of sites, without requiring any technical knowledge or even awareness of lazy-loading as a concept. Adopting the new loading attribute is a great chance for WordPress to lead the way for a faster web overall.

Technical Solution

The loading attribute currently supports two possible values:

  • eager, to load an image immediately on pageload
  • lazy, to load an image only when it becomes relevant for the viewport

The implementation seeks to enable lazy-loading images by default, providing the loading attribute with value lazy on the following img tags:

  • Images in post content
  • Images in post excerpts
  • Images in comments
  • Images in text widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. content
  • Individual images rendered via wp_get_attachment_image()
  • AvatarAvatar An avatar is an image or illustration that specifically refers to a character that represents an online user. It’s usually a square box that appears next to the user’s name. images rendered via get_avatar()

Note that loading="lazy" will only be added if the respective tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) does not yet include a loading attribute. In other words, to prevent an image from being lazy-loaded, it is recommended to specify loading="eager".

Customization for Developers

Note that the customization capabilities outlined below and how they work exactly is subject to change.

While the images outlined above will be lazy-loaded by default, developers will be able to override this behavior both globally and on a per-image basis.

A new filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. wp_lazy_loading_enabled will allow turning the feature on and off. For example, one could disable lazy-loading entirely with the following snippet:

add_filter( 'wp_lazy_loading_enabled', '__return_false' );

This filter also passes a secondary parameter $tag_name, which is a specific tag name to enable or disable lazy-loading for, and $context, which typically is the name of the current filter being run. Currently, img is the only supported value, but since adding loading support to additional tags is on the horizon (e.g. some browsers already support the loading attribute on iframe tags), this parameter exists for future compatibility. For example, if you want to be more specific and disable lazy-loading only for images (so that future supported tags would by default have it enabled), you could use the following snippet:

add_filter(
	'wp_lazy_loading_enabled',
	function( $result, $tag_name ) {
		if ( 'img' === $tag_name ) {
			return false;
		}
		return $result;
	},
	10,
	2
);

In addition to this filter which allows customization across the entire site, there is another filter wp_set_image_loading_attr that filters the value of the loading attribute for individual control per image. The filter passes the full img tag markup including all attributes as second parameter, the full content blob that the image is part of, and the context, which typically is the current filter being run. wp_set_image_loading_attr can for example be used for interoperability by plugins that currently use alternative mechanisms to lazy-load, for example a class or a data attribute. It is recommended to only do this as a transition though, and in the long run update such plugins to specify loading="eager", in which case coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. will leave that in place as is, as mentioned before.

Please see the inline documentation in the pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party for more detail on how to customize lazy-loading behavior.

Call for Testing

The proposed solution is available as a feature plugin WP Lazy Loading in the plugin repository. The plugin is being developed on GitHub. Your testing and feedback will be much appreciated. Particularly testing interoperability with various content creation mechanisms (e.g. blocks, shortcodes) and existing lazy-loading plugins would be helpful. The current goal is to get this feature released as part of WordPress 5.4, merging in the next two weeks.

Please share your ideas, questions and thoughts either in a comment on this post, in the plugin’s support forumSupport Forum WordPress Support Forums is a place to go for help and conversations around using WordPress. Also the place to go to report issues that are caused by errors with the WordPress code and implementations. https://en.forums.wordpress.com/. on wordpress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/, or on the GitHubGitHub GitHub is a website that offers online implementation of git repositories that can can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ repository.

#feature-lazyloading