How to Conditionally Load JavaScript for Gutenberg Blocks

WordPress 5.0 introduced a number of new block-related functions which super-charge developers with new tools to leverage the new Gutenberg WordPress block editor. Let’s take a look at one of those neat functions.

The goal of this guide is to review how we check for specific blocks on a page, and then conditionally load a relative JavaScript file on the front-end for that block. I use this method within CoBlocks and Block Gallery, to load front-end JavaScript only on pages where specific blocks are used.

Determine if post has a specific block

First up, let’s dive into the has_block function, introduced in WordPress 5.0. This function ultimately determines whether a post, or content string, contains a specific block type – based on the block name. It accepts two parameters:

  • $block_type – Name of the block we’re looking for
  • $post – Post content/id/object, which defaults to global $post

Below you’ll find the has_block` function in it’s simplest form:

if ( has_block( 'blockgallery/masonry' ) ) {
  // Do something, if the Block Gallery Masonry block is added to this page.

It’s important to note that a block’s name is the unique identifiable string registered for the block. Names are structured as namespace/block-name, where namespace is the name of the block plugin (or core, if you’re targeting a block within WordPress core).

You can learn more about block names and complete block registration on the official Gutenberg Handbook. If you’re just getting into block development, this handbook will be your best friend – bookmark it.

Conditionally load block front-end scripts

One of the best use cases I see for has_blocks is to conditionally load required JavaScript on a specific page, instead of site-wide.

Here is how I use has_blocks and wp_enqueue_scripts to look for the Block Gallery Masonry block within a page/post and enqueue it’s scripts:

blockgallery_frontend_scripts() {
	if ( has_block( 'blockgallery/masonry' ) ) {
        		plugins_url( 'dist/blockgallery-masonry.js', __FILE__ ),
			array( 'jquery', 'masonry', 'imagesloaded' ),
			filemtime( plugin_dir_path( __FILE__ ) . 'dist/blockgallery-masonry.js' )
add_action( 'wp_enqueue_scripts', 'blockgallery_frontend_scripts' );

And there you have it; no more loading numerous JavaScript on the front-end of a site, regardless of the content added to a page.

It’s important to note that this only currently works on singular pages/pages — not in the context of any blogroll (index, archive, search, etc.) templates. I’m not exactly sure why it doesn’t, but I have opened up an issue on GitHub to spread awareness on the issue/get some further insight.