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:
wp_enqueue_block_script → adds the script to the scriptHandles which ensures the file gets enqueued both in the editor and on the frontend
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'];
}
}
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:
wp_enqueue_block_script→ adds the script to thescriptHandleswhich ensures the file gets enqueued both in the editor and on the frontendwp_enqueue_block_view_script→ adds the script to theviewScriptHandleswhich ensures the file gets enqueued on the frontendHere is an example of how this function can get implemented: