Load block variation assets only when used
Published: – Leave a comment
Since WordPress 5.9 you can load assets for a block only when the block is used. For block styles/variations, you need to be creative, though. Especially if it’s not your own block you’re creating a variant of.
Since block variations are usually registered separately, and especially if you want to have it clean in a separate file or trying to extend an existing block, you cannot properly rely on something like register_block_type
to register your assets with the existing block. This is because this would need to overwriting the render_callback
property of said function and thus may break the block itself, since the original callback won’t be called anymore.
In my solution I use the render_block_{$this->name}
hook, where it’s possible since quite some time to allow registering assets via wp_enqueue_script
or wp_enqueue_style
.
To enqueue assets only for a block on certain conditions, I use the following code:
static function my_group_callback( string $block_content, array $block ): string {
if ( ! $condition ) { // check your condition
return $block_content;
}
\wp_enqueue_style( 'my-handle', $uri ); // adjust handle and uri
return $block_content;
}
\add_action( 'render_block_core/group', 'my_group_callback', 10, 2 );
Code language: PHP (php)
In this example, I enqueue a style if a certain condition is met in a group block. This code is a boilerplate, since $condition
and $uri
are not defined here. The real code checks for the className
attribute in $block['attrs']['className']
for a specific class that is added if my registered block variation is used. Only then the style is enqueued and loaded in the frontend.