Conditionally Load Block Assets

Published on:
Category: WordPress

Updated: see Part 2 post 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' ) ) {
} );

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 ) ) {
} );

You see it in action in my Juxtapose block source.


If you are developing a block that loads front-end assets, help out your users and add conditionally loading of the assets.


Darren Ethier February 17, 2020 Reply

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.

Mikael Korpela February 18, 2020 Reply

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

Here’s an example of that in Jetpack:

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

Andrew Duthie February 25, 2020 Reply

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.


Leave a Reply