diff --git a/src/wp-includes/script-loader.php b/src/wp-includes/script-loader.php index 42d42b3f8781d..6205071cbfd04 100644 --- a/src/wp-includes/script-loader.php +++ b/src/wp-includes/script-loader.php @@ -2797,6 +2797,18 @@ function wp_enqueue_registered_block_scripts_and_styles() { wp_enqueue_script( $script_handle ); } + /** + * Enqueue view script modules when block assets are loaded eagerly. + * + * This ensures parity with script and style handles, as modules are not + * automatically handled elsewhere when on-demand loading is disabled. + */ + if ( ! empty( $block_type->view_script_module_ids ) && function_exists( 'wp_enqueue_script_module' ) ) { + foreach ( $block_type->view_script_module_ids as $view_script_module_id ) { + wp_enqueue_script_module( $view_script_module_id ); + } + } + if ( $load_editor_scripts_and_styles ) { // Editor styles. foreach ( $block_type->editor_style_handles as $editor_style_handle ) { diff --git a/tests/phpunit/tests/blocks/wpEnqueueRegisteredBlockScriptsAndStyles.php b/tests/phpunit/tests/blocks/wpEnqueueRegisteredBlockScriptsAndStyles.php new file mode 100644 index 0000000000000..2ce091206a9de --- /dev/null +++ b/tests/phpunit/tests/blocks/wpEnqueueRegisteredBlockScriptsAndStyles.php @@ -0,0 +1,78 @@ +original_script_modules = $wp_script_modules; + $wp_script_modules = null; + } + + /** + * Save the original script modules instance. + */ + public function tear_down() { + global $wp_script_modules; + $wp_script_modules = $this->original_script_modules; + + $registry = WP_Block_Type_Registry::get_instance(); + if ( $registry->is_registered( 'test/block' ) ) { + $registry->unregister( 'test/block' ); + } + + remove_filter( 'should_load_block_assets_on_demand', '__return_false' ); + + parent::tear_down(); + } + + /** + * Tests that view script modules are enqueued when block assets are not loaded on demand. + * + * @ticket 64812 + */ + public function test_view_script_modules_enqueued_when_not_on_demand() { + add_filter( 'should_load_block_assets_on_demand', '__return_false' ); + + $module_id = 'test-module'; + + wp_register_script_module( $module_id, '/test.js' ); + + register_block_type( + 'test/block', + array( + 'view_script_module_ids' => array( $module_id ), + ) + ); + + wp_enqueue_registered_block_scripts_and_styles(); + + $this->assertContains( + $module_id, + wp_script_modules()->get_queue(), + 'Expected view script module to be enqueued.' + ); + } +}