From 211d94b71095bd41d88a0b054cbec74e18d2fc1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=83=C2=B3=C3=85=E2=80=9Akowski?= Date: Thu, 22 Jul 2021 08:36:11 +0000 Subject: [PATCH] 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 --- src/wp-includes/script-loader.php | 32 ++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/script-loader.php b/src/wp-includes/script-loader.php index e7dce405f8..55fcff8978 100644 --- a/src/wp-includes/script-loader.php +++ b/src/wp-includes/script-loader.php @@ -2436,13 +2436,39 @@ function wp_enqueue_registered_block_scripts_and_styles() { function enqueue_block_styles_assets() { $block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered(); - foreach ( $block_styles as $styles ) { + foreach ( $block_styles as $block_name => $styles ) { foreach ( $styles as $style_properties ) { if ( isset( $style_properties['style_handle'] ) ) { - wp_enqueue_style( $style_properties['style_handle'] ); + + // If the site loads separate styles per-block, enqueue the stylesheet on render. + if ( wp_should_load_separate_core_block_assets() ) { + add_filter( + 'render_block', + function( $html, $block ) use ( $style_properties ) { + wp_enqueue_style( $style_properties['style_handle'] ); + return $html; + } + ); + } else { + wp_enqueue_style( $style_properties['style_handle'] ); + } } if ( isset( $style_properties['inline_style'] ) ) { - wp_add_inline_style( 'wp-block-library', $style_properties['inline_style'] ); + + // Default to "wp-block-library". + $handle = 'wp-block-library'; + + // If the site loads separate styles per-block, check if the block has a stylesheet registered. + if ( wp_should_load_separate_core_block_assets() ) { + $block_stylesheet_handle = generate_block_asset_handle( $block_name, 'style' ); + global $wp_styles; + if ( isset( $wp_styles->registered[ $block_stylesheet_handle ] ) ) { + $handle = $block_stylesheet_handle; + } + } + + // Add inline styles to the calculated handle. + wp_add_inline_style( $handle, $style_properties['inline_style'] ); } } }