函数文档

wp_should_load_block_assets_on_demand()

💡 云策文档标注

概述

wp_should_load_block_assets_on_demand() 函数用于检查是否仅在块渲染时加载其样式资源。它影响前端页面中块资源的加载行为,默认返回值依赖于 wp_should_load_separate_core_block_assets() 的结果。

关键要点

  • 函数返回 true 时,块资源仅在渲染时加载;返回 false 时,所有块资源无论是否渲染都会被加载。
  • 默认返回值基于 wp_should_load_separate_core_block_assets() 的结果,控制核心块样式表是单独加载还是通过合并的 'wp-block-library' 样式表加载。
  • 此函数仅影响前端页面,不适用于块编辑器屏幕。
  • 可通过 should_load_block_assets_on_demand 过滤器钩子自定义返回值。

代码示例

function wp_should_load_block_assets_on_demand() {
	if ( is_admin() || is_feed() || wp_is_rest_endpoint() ) {
		return false;
	}

	$load_assets_on_demand = wp_should_load_separate_core_block_assets();

	return apply_filters( 'should_load_block_assets_on_demand', $load_assets_on_demand );
}

注意事项

  • 函数在管理界面、Feed 或 REST API 端点请求时始终返回 false,确保资源加载。
  • 引入于 WordPress 6.8.0 版本。

📄 原文内容

Checks whether block styles should be loaded only on-render.

Description

When this function returns true, other functions ensure that blocks only load their assets on-render.
When this function returns false, all block assets are loaded regardless of whether they are rendered in a page.

The default return value depends on the result of wp_should_load_separate_core_block_assets(), which controls whether Core block stylesheets should be loaded separately or via a combined ‘wp-block-library’ stylesheet.

This only affects front end and not the block editor screens.

See also

Return

bool Whether to load block assets only when they are rendered.

Source

function wp_should_load_block_assets_on_demand() {
	if ( is_admin() || is_feed() || wp_is_rest_endpoint() ) {
		return false;
	}

	/*
	 * For backward compatibility, the default return value for this function is based on the return value of
	 * `wp_should_load_separate_core_block_assets()`. Initially, this function used to control both of these concerns.
	 */
	$load_assets_on_demand = wp_should_load_separate_core_block_assets();

	/**
	 * Filters whether block styles should be loaded on demand.
	 *
	 * Returning false loads all block assets, regardless of whether they are rendered in a page or not.
	 * Returning true loads block assets only when they are rendered.
	 *
	 * The default value of the filter depends on the result of <a href="https://developer.wordpress.org/reference/functions/wp_should_load_separate_core_block_assets/">wp_should_load_separate_core_block_assets()</a>,
	 * which controls whether Core block stylesheets should be loaded separately or via a combined 'wp-block-library'
	 * stylesheet.
	 *
	 * @since 6.8.0
	 *
	 * @param bool $load_assets_on_demand Whether to load block assets only when they are rendered.
	 */
	return apply_filters( 'should_load_block_assets_on_demand', $load_assets_on_demand );
}

Hooks

apply_filters( ‘should_load_block_assets_on_demand’, bool $load_assets_on_demand )

Filters whether block styles should be loaded on demand.

Changelog

Version Description
6.8.0 Introduced.