函数文档

wp_load_classic_theme_block_styles_on_demand()

💡 云策文档标注

概述

wp_load_classic_theme_block_styles_on_demand() 函数用于在经典主题中按需加载块样式,通过添加钩子来优化性能。它确保仅在需要时加载块资源,避免无条件加载大型样式表。

关键要点

  • 函数仅适用于经典主题,如果是块主题则直接返回,不执行任何操作。
  • 通过添加过滤器 wp_should_output_buffer_template_for_enhancement 来启用模板增强输出缓冲。
  • 添加过滤器 should_load_separate_core_block_assets 和 should_load_block_assets_on_demand,以按需加载核心块样式和块资源。
  • 在输出缓冲启动后,添加动作 wp_template_enhancement_output_buffer_started 来调用 wp_hoist_late_printed_styles。

注意事项

  • 函数优先级设置为0,便于主题开发者轻松覆盖或禁用相关功能。
  • 如果站点已明确禁用输出缓冲或按需加载,函数会提前返回,避免不必要的操作。

📄 原文内容

Adds hooks to load block styles on demand in classic themes.

Description

See also

Source

function wp_load_classic_theme_block_styles_on_demand() {
	// This is not relevant to block themes, as they are opted in to loading separate styles on demand via _add_default_theme_supports().
	if ( wp_is_block_theme() ) {
		return;
	}

	/*
	 * Make sure that wp_should_output_buffer_template_for_enhancement() returns true even if there aren't any
	 * `wp_template_enhancement_output_buffer` filters added, but do so at priority zero so that applications which
	 * wish to stream responses can more easily turn this off.
	 */
	add_filter( 'wp_should_output_buffer_template_for_enhancement', '__return_true', 0 );

	// If a site has opted out of the template enhancement output buffer, then bail.
	if ( ! wp_should_output_buffer_template_for_enhancement() ) {
		return;
	}

	// The following two filters are added by default for block themes in _add_default_theme_supports().

	/*
	 * Load separate block styles so that the large block-library stylesheet is not enqueued unconditionally, and so
	 * that block-specific styles will only be enqueued when they are used on the page. A priority of zero allows for
	 * this to be easily overridden by themes which wish to opt out. If a site has explicitly opted out of loading
	 * separate block styles, then abort.
	 */
	add_filter( 'should_load_separate_core_block_assets', '__return_true', 0 );
	if ( ! wp_should_load_separate_core_block_assets() ) {
		return;
	}

	/*
	 * Also ensure that block assets are loaded on demand (although the default value is from should_load_separate_core_block_assets).
	 * As above, a priority of zero allows for this to be easily overridden by themes which wish to opt out. If a site
	 * has explicitly opted out of loading block styles on demand, then abort.
	 */
	add_filter( 'should_load_block_assets_on_demand', '__return_true', 0 );
	if ( ! wp_should_load_block_assets_on_demand() ) {
		return;
	}

	// Add hooks which require the presence of the output buffer. Ideally the above two filters could be added here, but they run too early.
	add_action( 'wp_template_enhancement_output_buffer_started', 'wp_hoist_late_printed_styles' );
}

Changelog

Version Description
6.9.0 Introduced.