Skip to content

Commit 211d94b

Browse files
committed
Editor: Conditionally load registered styles for block variations
In WordPress 5.8 we added the ability to only load styles for blocks when these blocks are rendered. However, these optimizations left out block-styles that get added using the register_block_style() function/API. Props aristath. Fixes #53616. git-svn-id: https://develop.svn.wordpress.org/trunk@51471 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 92c454c commit 211d94b

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

src/wp-includes/script-loader.php

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2436,13 +2436,39 @@ function wp_enqueue_registered_block_scripts_and_styles() {
24362436
function enqueue_block_styles_assets() {
24372437
$block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered();
24382438

2439-
foreach ( $block_styles as $styles ) {
2439+
foreach ( $block_styles as $block_name => $styles ) {
24402440
foreach ( $styles as $style_properties ) {
24412441
if ( isset( $style_properties['style_handle'] ) ) {
2442-
wp_enqueue_style( $style_properties['style_handle'] );
2442+
2443+
// If the site loads separate styles per-block, enqueue the stylesheet on render.
2444+
if ( wp_should_load_separate_core_block_assets() ) {
2445+
add_filter(
2446+
'render_block',
2447+
function( $html, $block ) use ( $style_properties ) {
2448+
wp_enqueue_style( $style_properties['style_handle'] );
2449+
return $html;
2450+
}
2451+
);
2452+
} else {
2453+
wp_enqueue_style( $style_properties['style_handle'] );
2454+
}
24432455
}
24442456
if ( isset( $style_properties['inline_style'] ) ) {
2445-
wp_add_inline_style( 'wp-block-library', $style_properties['inline_style'] );
2457+
2458+
// Default to "wp-block-library".
2459+
$handle = 'wp-block-library';
2460+
2461+
// If the site loads separate styles per-block, check if the block has a stylesheet registered.
2462+
if ( wp_should_load_separate_core_block_assets() ) {
2463+
$block_stylesheet_handle = generate_block_asset_handle( $block_name, 'style' );
2464+
global $wp_styles;
2465+
if ( isset( $wp_styles->registered[ $block_stylesheet_handle ] ) ) {
2466+
$handle = $block_stylesheet_handle;
2467+
}
2468+
}
2469+
2470+
// Add inline styles to the calculated handle.
2471+
wp_add_inline_style( $handle, $style_properties['inline_style'] );
24462472
}
24472473
}
24482474
}

0 commit comments

Comments
 (0)