Skip to content

Commit

Permalink
Script Modules API: Add import map polyfill (#58263)
Browse files Browse the repository at this point in the history
* Add import map polyfill

* Update issue number

* Update WP folder for the polyfill file

* Update the function with dom injection

* Load it on the footer

* Remove unwanted comma

* Update WP Core folder to be like other polyfills

* Do not load polyfill if there are no modules

* Add an id to the script

* Use WP default functions

* Use load id

* Use stable version

* Sync function with Core
  • Loading branch information
cbravobernal authored Feb 1, 2024
1 parent 726c5c6 commit 89a15cc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
27 changes: 27 additions & 0 deletions lib/compat/wordpress-6.5/class-wp-script-modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,37 @@ public function print_script_module_preloads() {
* Prints the import map using a script tag with a type="importmap" attribute.
*
* @since 6.5.0
*
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing the polyfill.
*/
public function print_import_map() {
$import_map = $this->get_import_map();
if ( ! empty( $import_map['imports'] ) ) {
global $wp_scripts;
if ( isset( $wp_scripts ) ) {
/*
* In Core, the polyfill is registered with a different approach.
* See: https://github.com/WordPress/wordpress-develop/blob/4b23ba81ddb067110e41d05550de7f2a4f09dad3/src/wp-includes/script-loader.php#L99
*/
wp_register_script(
'wp-polyfill-importmap',
gutenberg_url( '/build/modules/importmap-polyfill.min.js' ),
array(),
'1.8.2',
true
);
wp_print_inline_script_tag(
wp_get_script_polyfill(
$wp_scripts,
array(
'HTMLScriptElement.supports && HTMLScriptElement.supports("importmap")' => 'wp-polyfill-importmap',
)
),
array(
'id' => 'wp-load-polyfill-importmap',
)
);
}
wp_print_inline_script_tag(
wp_json_encode( $import_map, JSON_HEX_TAG | JSON_HEX_AMP ),
array(
Expand Down
11 changes: 6 additions & 5 deletions lib/compat/wordpress-6.5/scripts-modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@
* @return WP_Script_Modules The main WP_Script_Modules instance.
*/
function wp_script_modules(): WP_Script_Modules {
static $instance = null;
if ( is_null( $instance ) ) {
$instance = new WP_Script_Modules();
$instance->add_hooks();
global $wp_script_modules;

if ( ! ( $wp_script_modules instanceof WP_Script_Modules ) ) {
$wp_script_modules = new WP_Script_Modules();
}
return $instance;
return $wp_script_modules;
}
wp_script_modules()->add_hooks();
}

if ( ! function_exists( 'wp_register_script_module' ) ) {
Expand Down

0 comments on commit 89a15cc

Please sign in to comment.