Conditionally Load Block Assets

Updated: see Part 2 post that explains a better way, as pointed out in the comments.

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.

Comments

  1. Another alternative if the block is also registered php side is to use the `render_callback` function registered with the block to enqueue the assets for that block.

    1. > Another alternative if the block is also registered php side is to use the `render_callback`

      Here’s an example of that in Jetpack: https://github.com/Automattic/jetpack/blob/856c557a92069981653cdf8a0b4c5edcc454ca96/extensions/blocks/slideshow/slideshow.php#L10-L31

      I wonder if the two methods have any difference performance-wise for lengthier posts?

  2. While it eventually lost steam, there was quite a bit of early discussion on how this sort of optimization could be automated on behalf of the block implementer. It would be nice if this effort could be revived. I do recall that it had some very difficult technical hurdles to overcome.

    See: https://github.com/WordPress/gutenberg/issues/5445

Add a comment

Your email address will not be published. Required fields are marked *