| 1 |
<?php |
| 2 |
/** |
| 3 |
* Utils to optimize the interactive scripts. |
| 4 |
* |
| 5 |
* @package Gutenberg |
| 6 |
* @subpackage Interactivity API |
| 7 |
*/ |
| 8 |
|
| 9 |
/** |
| 10 |
* Makes sure that interactivity scripts execute after all `wp_store` directives have been printed to the page. |
| 11 |
* |
| 12 |
* In WordPress 6.3+ this is achieved by printing in the head but marking the scripts with defer. This has the benefit |
| 13 |
* of early discovery so the script is loaded by the browser, while at the same time not blocking rendering. In older |
| 14 |
* versions of WordPress, this is achieved by loading the scripts in the footer. |
| 15 |
* |
| 16 |
* @link https://make.wordpress.org/core/2023/07/14/registering-scripts-with-async-and-defer-attributes-in-wordpress-6-3/ |
| 17 |
*/ |
| 18 |
function gutenberg_interactivity_move_interactive_scripts_to_the_footer() { |
| 19 |
$supports_defer = version_compare( strtok( get_bloginfo( 'version' ), '-' ), '6.3', '>=' ); |
| 20 |
if ( $supports_defer ) { |
| 21 |
// Defer execution of @wordpress/interactivity package but continue loading in head. |
| 22 |
wp_script_add_data( 'wp-interactivity', 'strategy', 'defer' ); |
| 23 |
wp_script_add_data( 'wp-interactivity', 'group', 0 ); |
| 24 |
} else { |
| 25 |
// Move the @wordpress/interactivity package to the footer. |
| 26 |
wp_script_add_data( 'wp-interactivity', 'group', 1 ); |
| 27 |
} |
| 28 |
|
| 29 |
// Move all the view scripts of the interactive blocks to the footer. |
| 30 |
$registered_blocks = \WP_Block_Type_Registry::get_instance()->get_all_registered(); |
| 31 |
foreach ( array_values( $registered_blocks ) as $block ) { |
| 32 |
if ( isset( $block->supports['interactivity'] ) && $block->supports['interactivity'] ) { |
| 33 |
foreach ( $block->view_script_handles as $handle ) { |
| 34 |
// Note that all block view scripts are already made defer by default. |
| 35 |
wp_script_add_data( $handle, 'group', $supports_defer ? 0 : 1 ); |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
add_action( 'wp_enqueue_scripts', 'gutenberg_interactivity_move_interactive_scripts_to_the_footer', 11 ); |
| 41 |
|