函数文档

wp_preload_resources()

💡 云策文档标注

概述

wp_preload_resources() 函数用于向浏览器输出资源预加载指令,以提升页面渲染性能。它通过过滤器 wp_preload_resources 接收资源数组,处理并生成唯一的 HTML 预加载标签。

关键要点

  • 函数核心功能是打印资源预加载指令,确保关键资源提前加载,减少渲染阻塞。
  • 通过 apply_filters('wp_preload_resources', array()) 过滤器允许开发者自定义预加载资源列表。
  • 支持多种资源属性,如 href、as、crossorigin、type、media、imagesrcset、imagesizes 和 fetchpriority。
  • 函数会去重资源(基于 href 或 imagesrcset),并忽略非标量值或不支持的属性。
  • 预加载应仅用于渲染阻塞资源,避免与非阻塞资源竞争,否则可能拖慢渲染速度。

代码示例

// 示例:通过过滤器添加预加载资源
add_filter('wp_preload_resources', function($preload_resources) {
    $preload_resources[] = [
        'href' => 'https://example.com/script.js',
        'as' => 'script',
        'crossorigin' => 'anonymous'
    ];
    return $preload_resources;
});

注意事项

  • imagesrcset 和 imagesizes 属性仅在 as 为 'image' 时有效,且 imagesizes 需要 imagesrcset 存在。
  • 非标量属性值会被忽略,确保资源值为字符串或数字类型。
  • 函数使用 esc_url() 和 esc_attr() 进行安全转义,防止 XSS 攻击。

📄 原文内容

Prints resource preloads directives to browsers.

Description

Gives directive to browsers to preload specific resources that website will need very soon, this ensures that they are available earlier and are less likely to block the page’s render. Preload directives should not be used for non-render-blocking elements, as then they would compete with the render-blocking ones, slowing down the render.

These performance improving indicators work by using <link rel="preload">.

Source

function wp_preload_resources() {
	/**
	 * Filters domains and URLs for resource preloads.
	 *
	 * @since 6.1.0
	 * @since 6.6.0 Added the `$fetchpriority` attribute.
	 *
	 * @param array  $preload_resources {
	 *     Array of resources and their attributes, or URLs to print for resource preloads.
	 *
	 *     @type array ...$0 {
	 *         Array of resource attributes.
	 *
	 *         @type string $href          URL to include in resource preloads. Required.
	 *         @type string $as            How the browser should treat the resource
	 *                                     (`script`, `style`, `image`, `document`, etc).
	 *         @type string $crossorigin   Indicates the CORS policy of the specified resource.
	 *         @type string $type          Type of the resource (`text/html`, `text/css`, etc).
	 *         @type string $media         Accepts media types or media queries. Allows responsive preloading.
	 *         @type string $imagesizes    Responsive source size to the source Set.
	 *         @type string $imagesrcset   Responsive image sources to the source set.
	 *         @type string $fetchpriority Fetchpriority value for the resource.
	 *     }
	 * }
	 */
	$preload_resources = apply_filters( 'wp_preload_resources', array() );

	if ( ! is_array( $preload_resources ) ) {
		return;
	}

	$unique_resources = array();

	// Parse the complete resource list and extract unique resources.
	foreach ( $preload_resources as $resource ) {
		if ( ! is_array( $resource ) ) {
			continue;
		}

		$attributes = $resource;
		if ( isset( $resource['href'] ) ) {
			$href = $resource['href'];
			if ( isset( $unique_resources[ $href ] ) ) {
				continue;
			}
			$unique_resources[ $href ] = $attributes;
			// Media can use imagesrcset and not href.
		} elseif ( ( 'image' === $resource['as'] ) &&
			( isset( $resource['imagesrcset'] ) || isset( $resource['imagesizes'] ) )
		) {
			if ( isset( $unique_resources[ $resource['imagesrcset'] ] ) ) {
				continue;
			}
			$unique_resources[ $resource['imagesrcset'] ] = $attributes;
		} else {
			continue;
		}
	}

	// Build and output the HTML for each unique resource.
	foreach ( $unique_resources as $unique_resource ) {
		$html = '';

		foreach ( $unique_resource as $resource_key => $resource_value ) {
			if ( ! is_scalar( $resource_value ) ) {
				continue;
			}

			// Ignore non-supported attributes.
			$non_supported_attributes = array( 'as', 'crossorigin', 'href', 'imagesrcset', 'imagesizes', 'type', 'media', 'fetchpriority' );
			if ( ! in_array( $resource_key, $non_supported_attributes, true ) && ! is_numeric( $resource_key ) ) {
				continue;
			}

			// imagesrcset only usable when preloading image, ignore otherwise.
			if ( ( 'imagesrcset' === $resource_key ) && ( ! isset( $unique_resource['as'] ) || ( 'image' !== $unique_resource['as'] ) ) ) {
				continue;
			}

			// imagesizes only usable when preloading image and imagesrcset present, ignore otherwise.
			if ( ( 'imagesizes' === $resource_key ) &&
				( ! isset( $unique_resource['as'] ) || ( 'image' !== $unique_resource['as'] ) || ! isset( $unique_resource['imagesrcset'] ) )
			) {
				continue;
			}

			$resource_value = ( 'href' === $resource_key ) ? esc_url( $resource_value, array( 'http', 'https' ) ) : esc_attr( $resource_value );

			if ( ! is_string( $resource_key ) ) {
				$html .= " $resource_value";
			} else {
				$html .= " $resource_key='$resource_value'";
			}
		}
		$html = trim( $html );

		printf( "<link rel='preload' %s />n", $html );
	}
}

Hooks

apply_filters( ‘wp_preload_resources’, array $preload_resources )

Filters domains and URLs for resource preloads.

Changelog

Version Description
6.1.0 Introduced.