Conditionally Load Block Assets
Updated: see Conditionally Load Block Assets, Part 2 that explains a better way, as pointed out in the comments. Or see the newer Part 3 post with an even easier way with WP 5.8.
One of the great features of the WordPress Block Editor is all the specialty blocks that can be created. This can also be the downside, each of these niche blocks might load their own view assets; and if not done right, all these assets could load on every page. Web. Bloat.
View assets are typically JavaScript or CSS that need to be loaded on the front-end to display the block properly. One example is my juxtapose block that loads both an extra JS and CSS file.
To load the assets properly, I want to add a check if the page contains that block or not. The built-in WordPress function has_block() checks a post's content if it contains a specific block.
To use, you can include a check in your enqueue hook like so:
add_action( 'wp_enqueue_scripts', function() {
if ( has_block( 'mkaz/juxtapose-block' ) ) {
juxtapose_view_assets();
}
} );
In the above example, the juxtapose_view_assets()
function calls the wp_enqueue_style()
and wp_enqueue_script
functions to add the needed view files.
There is one issue with the above, it will only work on singular pages, a page that only contains a single post. It will not detect a block present on an index or list page with multiple posts.
For that, you need to loop through all posts and check if each one has the block, for example:
add_action( 'wp_enqueue_scripts', function() {
global $posts;
foreach ( $posts as $post ) {
if ( has_block( 'mkaz/juxtapose-block', $post ) ) {
juxtapose_view_assets();
return;
}
}
} );
You see it in action in my Juxtapose block source.
Summary
If you are developing a block that loads front-end assets, help out your users and add conditionally loading of the assets.