Skip to content

Blocks: Add new utility function to add script / viewScript to an already registered block #48382

@fabiankaegy

Description

@fabiankaegy

What problem does this address?

Part of #41236.

There are many use-cases why one may want to add additional frontend javascript to existing blocks. This is both for core and custom blocks.

What is your proposed solution?

We already have a really solid system in place for handling the enqueue logic for the scripts that get defined in the block registration. We also have a utility function in core that allows you to add additional styles to any block called wp_enqueue_block_style.

My suggestion here would be to introduce two more similar functions:

  1. wp_enqueue_block_script → adds the script to the scriptHandles which ensures the file gets enqueued both in the editor and on the frontend
  2. wp_enqueue_block_view_script → adds the script to the viewScriptHandles which ensures the file gets enqueued on the frontend

Here is an example of how this function can get implemented:

/**
  * Enqueue a view script for a block
  *
  * @param string $block_name Block name.
  * @param array  $args {
  *    Optional. Array of arguments for enqueuing a view script.
  *    @type string $handle Script handle.
  *    @type string $src Script URL.
  *    @type array $dep Script dependencies.
  *    @type string|bool $ver Script version.
  *    @type bool $in_footer Whether to enqueue the script before </body> instead of in the <head>.
  * }
  * @return void
  */
 function wp_enqueue_block_view_script( $block_name, $args = array() ) {
 	$default_args = array(
 		'handle'    => '',
 		'src'       => '',
 		'dep'       => array(),
 		'ver'       => false,
 		'in_footer' => [ 'strategy' => 'defer' ],
 	);

 	$args = wp_parse_args( $args, $default_args );

 	$block = \WP_Block_Type_Registry::get_instance()->get_registered( $block_name );

 	wp_register_script(
 		$args['handle'],
 		$args['src'],
 		$args['dep'],
 		$args['ver'],
 		$args['in_footer']
 	);

 	if ( ! empty( $block ) ) {
 		$block->view_script_handles[] = $args['handle'];
 	}
 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs DevReady for, and needs developer efforts[Feature] Block APIAPI that allows to express the block paradigm.[Feature] ExtensibilityThe ability to extend blocks or the editing experience[Feature] Interactivity APIAPI to add frontend interactivity to blocks.[Type] EnhancementA suggestion for improvement.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions