函数文档

wp_omit_loading_attr_threshold()

💡 云策文档标注

概述

wp_omit_loading_attr_threshold() 函数用于获取不延迟加载的前几个内容媒体元素的阈值。它通过 'wp_omit_loading_attr_threshold' 过滤器实现,默认阈值为 3,且通常每个页面加载只运行一次。

关键要点

  • 函数返回一个整数,表示不添加 `loading` 属性的内容媒体元素数量。
  • 使用静态变量 $omit_threshold 缓存结果,除非 $force 参数为 true,否则过滤器只应用一次。
  • 默认阈值从 5.9.0 版本的 1 更改为 6.3.0 版本的 3。
  • 通过 apply_filters('wp_omit_loading_attr_threshold', 3) 允许开发者自定义阈值。

代码示例

function wp_omit_loading_attr_threshold( $force = false ) {
	static $omit_threshold;

	if ( ! isset( $omit_threshold ) || $force ) {
		$omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 3 );
	}

	return $omit_threshold;
}

注意事项

  • 函数主要用于优化加载性能,影响媒体元素的 `loading` 属性设置。
  • 相关函数包括 wp_get_loading_optimization_attributes() 和 wp_get_loading_attr_default()。

📄 原文内容

Gets the threshold for how many of the first content media elements to not lazy-load.

Description

This function runs the ‘wp_omit_loading_attr_threshold’ filter, which uses a default threshold value of 3.
The filter is only run once per page load, unless the $force parameter is used.

Parameters

$forcebooloptional
If set to true, the filter will be (re-)applied even if it already has been before.

Default:false

Return

int The number of content media elements to not lazy-load.

Source

function wp_omit_loading_attr_threshold( $force = false ) {
	static $omit_threshold;

	// This function may be called multiple times. Run the filter only once per page load.
	if ( ! isset( $omit_threshold ) || $force ) {
		/**
		 * Filters the threshold for how many of the first content media elements to not lazy-load.
		 *
		 * For these first content media elements, the `loading` attribute will be omitted. By default, this is the case
		 * for only the very first content media element.
		 *
		 * @since 5.9.0
		 * @since 6.3.0 The default threshold was changed from 1 to 3.
		 *
		 * @param int $omit_threshold The number of media elements where the `loading` attribute will not be added. Default 3.
		 */
		$omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 3 );
	}

	return $omit_threshold;
}

Hooks

apply_filters( ‘wp_omit_loading_attr_threshold’, int $omit_threshold )

Filters the threshold for how many of the first content media elements to not lazy-load.

Changelog

Version Description
5.9.0 Introduced.