wp_get_loading_attr_default() WordPress Function

The wp_get_loading_attr_default() function is used to get the default loading attribute for a given tag.

wp_get_loading_attr_default( string $context ) #

Gets the default value to use for a loading attribute on an element.


Description

This function should only be called for a tag and context if lazy-loading is generally enabled.

The function usually returns ‘lazy’, but uses certain heuristics to guess whether the current element is likely to appear above the fold, in which case it returns a boolean false, which will lead to the loading attribute being omitted on the element. The purpose of this refinement is to avoid lazy-loading elements that are within the initial viewport, which can have a negative performance impact.

Under the hood, the function uses wp_increase_content_media_count() every time it is called for an element within the main content. If the element is the very first content element, the loading attribute will be omitted. This default threshold of 1 content element to omit the loading attribute for can be customized using the ‘wp_omit_loading_attr_threshold’ filter.


Top ↑

Parameters

$context

(string)(Required)Context for the element for which the loading attribute value is requested.


Top ↑

Return

(string|bool) The default loading attribute value. Either 'lazy', 'eager', or a boolean false, to indicate that the loading attribute should be skipped.


Top ↑

Source

File: wp-includes/media.php

function wp_get_loading_attr_default( $context ) {
	// Only elements with 'the_content' or 'the_post_thumbnail' context have special handling.
	if ( 'the_content' !== $context && 'the_post_thumbnail' !== $context ) {
		return 'lazy';
	}

	// Only elements within the main query loop have special handling.
	if ( is_admin() || ! in_the_loop() || ! is_main_query() ) {
		return 'lazy';
	}

	// Increase the counter since this is a main query content element.
	$content_media_count = wp_increase_content_media_count();

	// If the count so far is below the threshold, return `false` so that the `loading` attribute is omitted.
	if ( $content_media_count <= wp_omit_loading_attr_threshold() ) {
		return false;
	}

	// For elements after the threshold, lazy-load them as usual.
	return 'lazy';
}


Top ↑

Changelog

Changelog
VersionDescription
5.9.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More