should_load_separate_core_block_assets
云策文档标注
概述
should_load_separate_core_block_assets 是一个 WordPress 过滤器,用于控制核心区块样式是否按需加载。默认情况下,所有核心区块资源都会被加载,无论页面是否渲染这些区块;通过此过滤器可以优化性能,仅加载实际使用的区块资源。
关键要点
- 过滤器名称:should_load_separate_core_block_assets,默认返回 false,加载所有核心区块资源。
- 返回 true 时,仅加载页面中渲染的核心区块资源,提升网站性能。
- 在块主题中,默认值会自动改为 true,但可通过过滤器覆盖。
- 从 WordPress 6.4 版本起,若需在块主题中强制加载所有样式,需设置优先级为 11。
- 此过滤器可能影响第三方区块资源加载,需注意兼容性问题。
- 启用后,样式可能加载在 body 标签末尾而非 head,可能影响 W3C 验证。
代码示例
// 启用按需加载核心区块资源
add_filter( 'should_load_separate_core_block_assets', '__return_true' );
// 在块主题中强制加载所有核心区块资源(WordPress 6.4+)
add_filter( 'should_load_separate_core_block_assets', '__return_false', 11 );注意事项
- 过滤器名称可能误导,实际可能影响第三方区块资源,使用时需测试。
- 启用后,样式加载位置变化可能导致 W3C 验证问题,需权衡利弊。
- 建议在开发环境中验证效果,确保不影响网站功能和性能。
原文内容
Filters whether block styles should be loaded separately.
Description
Returning false loads all core block assets, regardless of whether they are rendered in a page or not. Returning true loads core block assets only when they are rendered.
Parameters
$load_separate_assetsbool-
Whether separate assets will be loaded.
Default false (all block assets are loaded, even when not used).
Source
return apply_filters( 'should_load_separate_core_block_assets', false );
Changelog
| Version | Description |
|---|---|
| 5.8.0 | Introduced. |
Skip to note 5 content
Fabian Kaegy
Also whilst the default value of this filter is
falseit actually gets changed totrueby default for any block theme.Skip to note 6 content
Oliver Campion
Since v6.4 you need to add a priority of 11 for this filter to work if you are trying to force block themes to load all block styles rather than just those which WordPress detects are being used …
add_filter( 'should_load_separate_core_block_assets', '__return_false', 11 );Skip to note 7 content
Will Skora
This hook is poorly named: when returning `true` with this hook; many 3rd-party blocks’ assets (JS and CSS) will only load when those blocks are being used on a page; slightly speeding up your website.
To use:
add_filter( 'should_load_separate_core_block_assets', '__return_true' );it only needs to be added once for each instance of WordPress you are working with; you do not need to add for each block or plugin that you wish to conditionally load.Skip to note 8 content
fredbir
It should be noted that using this hook will then load inline styles in the body of the website and not the head, which will invalidate your website on W3C validator.