Enable Only loading Styles for blocks Used on the page

New WordPress features with block or hybrid themes are coming fast and furious these days, and it is difficult to find documentation on all the new features. I remember reading that only styles for the blocks used on the page would be added to pages. However, I noticed my custom hybrid theme was adding all block styles to all pages. (I am using blocks.json to register my custom blocks, and my hybrid theme sets up styles in theme.json – which is required for this to work.) A little googling, and I found a post on Make WordPress Core blog that explains how to fix this.

All it takes is one filter added to your custom block or hybrid theme’s functions.php to make block or hybrid themes only load styles (core block styles, and styles set up in theme.json or block.json) when needed:

add_filter( 'should_load_separate_core_block_assets', '__return_true' );

Easy answer if you know what to look for and where to look.

Details on what that filter does below (copied from the Make WordPress post):

  • The wp-block-library stylesheet changes: Instead of loading the wp-includes/css/dist/block-library/style.css file which contains all styles for all blocks, this handle will now load the (much smaller) wp-includes/css/dist/block-library/common.css file, which contains generic styles like the default colors definitions, basic styles for text alignments, and styles for the .screen-reader-text class.
  • Styles for blocks will only get enqueued when the block gets rendered on a page.

Note: I am pretty sure this filter only automatically works for core blocks, and blocks that are registered with blocks.json. If your block stylesheets are added using wp_enqueue_style, they will still be added to all pages.

Inline custom styles for core blocks

The Make WordPress post also has instructions on how to inline additional styles for core blocks only if the block is on the page. It is under the headline (no anchor, unfortunately): “Taking advantage of separate styles loading to add plugin/theme styles to blocks”.