wp_preload_resources
云策文档标注
概述
wp_preload_resources 是一个 WordPress 过滤器,用于过滤资源预加载的域名和 URL。它允许开发者自定义需要预加载的资源列表,以优化页面加载性能。
关键要点
- 过滤器名称:wp_preload_resources,用于修改资源预加载数组。
- 参数:$preload_resources 是一个数组,包含资源属性或 URL,用于生成预加载指令。
- 资源属性:包括 href(必需)、as、crossorigin、type、media、imagesizes、imagesrcset 和 fetchpriority。
- 相关函数:wp_preload_resources() 在 wp-includes/general-template.php 中,用于向浏览器输出预加载指令。
- 版本更新:WordPress 6.6.0 添加了 $fetchpriority 属性,6.1.0 引入此过滤器。
代码示例
function craftedat_preload_assets( array $preload_resources ): array {
/**
* Check if stylesheet is loaded.
* 'theme-style' is the WP handle of your stylesheet.
*/
if ( wp_style_is( 'theme-style' ) ) {
$wp_style_theme = wp_styles()->registered['theme-style'];
// Including the version number is crucial.
$path_to_theme_styles = $wp_style_theme->src . '?ver=' . $wp_style_theme->ver;
$preload_resources[] = array(
'href' => $path_to_theme_styles,
'as' => 'style',
'media' => 'all',
'type' => 'text/css',
);
}
return $preload_resources;
}
add_filter( 'wp_preload_resources', 'craftedat_preload_assets' );注意事项
- 使用此过滤器时,需确保资源属性设置正确,例如 href 为必需项。
- 示例代码展示了如何预加载主题样式表,注意包含版本号以避免缓存问题。
- 过滤器在 WordPress 6.1.0 及以上版本可用,新属性如 fetchpriority 在 6.6.0 添加。
原文内容
Filters domains and URLs for resource preloads.
Parameters
$preload_resourcesarray-
Array of resources and their attributes, or URLs to print for resource preloads.
...$0arrayArray of resource attributes.hrefstringURL to include in resource preloads. Required.asstringHow the browser should treat the resource (script,style,image,document, etc).crossoriginstringIndicates the CORS policy of the specified resource.typestringType of the resource (text/html,text/css, etc).mediastringAccepts media types or media queries. Allows responsive preloading.imagesizesstringResponsive source size to the source Set.imagesrcsetstringResponsive image sources to the source set.fetchprioritystringFetchpriority value for the resource.
Source
$preload_resources = apply_filters( 'wp_preload_resources', array() );Changelog
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Skip to note 2 content
Robert C.
This is how you could use the
wp_preload_resourcesfilter to preload your theme styles.function craftedat_preload_assets( array $preload_resources ): array { /** * Check if stylesheet is loaded. * 'theme-style' is the WP handle of your stylesheet. */ if ( wp_style_is( 'theme-style' ) ) { $wp_style_theme = wp_styles()->registered['theme-style']; // Including the version number is crucial. $path_to_theme_styles = $wp_style_theme->src . '?ver=' . $wp_style_theme->ver; $preload_resources[] = array( 'href' => $path_to_theme_styles, 'as' => 'style', 'media' => 'all', 'type' => 'text/css', ); } return $preload_resources; } add_filter( 'wp_preload_resources', 'craftedat_preload_assets' );