wp_enqueue_block_style equivalent for scripts
Published: – Leave a comment
Since WordPress 5.9, there is the new function wp_enqueue_block_style
to enqueue block styles only if necessary, which means only if the associated block is rendered on the current page. While this is a huge benefit, there is no support for scripts. So if your block requires certain JavaScript only for the frontend, there’s no ready-to-use function within WordPress.
Fortunately, WordPress 5.9 also added the attribute view_script
to the register_block_type
function, which allows to set a script handle, that is only enqueued if the associated block is rendered on the current page. With WordPress 6.1, this attribute has been deprecated in favor of the new view_script_handles
, which allows defining multiple script handles to add. So for compatibility reasons, we can use both variants for now:
register_block_type(
'my/block',
[
// since WP 5.9
'view_script' => 'my-block-script',
// since WP 6.1
'view_script_handles' => [
'my-block-script',
],
],
);
Code language: PHP (php)
Here we register the block my/block
(I left out the other attributes here) and define a view script with the handle my-block-script
. This function can be called outside of any hooks.
We now need to make sure our frontend script is registered as per usual:
/**
* Register frontend assets.
*/
public function my_register_frontend_assets(): void {
$file_path = plugin_dir_path( __FILE__ ) . 'assets/js/file.js';
$file_url = plugin_dir_url( __FILE__ ) . 'assets/js/file.js';
wp_register_script( 'my-block-script', $file_url, [], filemtime( $file_path ), true );
}
add_action( 'init', 'my_register_frontend_assets' );
Code language: PHP (php)
Since the view script is enqueued via wp_enqueue_scripts
, make sure you register your script before that and see the magic happen. ✨