How to Conditionally Load Front-end JavaScript for Gutenberg Blocks

How to Conditionally Load Front-end 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:

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:

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.

Leave a Reply

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

Up Next:

New Shape Divider, Features and Icon Blocks in CoBlocks 1.9

New Shape Divider, Features and Icon Blocks in CoBlocks 1.9