Load scripts with WordPress core blocks on the front end

There may be time when you want to load a script with a block on the front-end of your site but not in the editor. This is much easier if this is your own block as you can add the script declaration in your block.json file.

When it comes to core blocks it is a little more difficult. You could use the enqueue_block_editor_assets hook, but this adds to both the front end and the admin.

Here is one way you can do this using the block_type_metadata_settings filter in WordPress.

<?php
/**
 * Registers the JS for the embed block.
 */
function hd_register_embed_block_js() {

	wp_register_script(
		'hd-embed-js',
		get_stylesheet_directory_uri() . '/assets/js/hd-embed.js',
		[],
		'1.0',
		true
	);

}

add_action( 'wp_enqueue_scripts', 'hd_register_embed_block_js' );

/**
 * Filters the block.json for the core/embed block to add the js script.
 *
 * @param  array $settings The block settings.
 * @param  array $metadata The block metadata.
 *
 * @return array $settings The block settings.
 */
function hd_filter_embed_block_meta_settings( $settings, $metadata ) {

	// if this is not the embed block.
	if ( 'core/embed' !== $metadata['name'] ) {
		return $settings;
	}

	// set the script settings to the register script name.
	$settings['script'] = [ 'hd-embed-js' ];

	// return the settings.
	return $settings;

}

add_filter( 'block_type_metadata_settings', 'hd_filter_embed_block_meta_settings', 10, 2 );