Last active
January 23, 2023 13:40
-
-
Save UVLabs/51a3258257923c7e35037eff5f71e20c to your computer and use it in GitHub Desktop.
Turns a WordPress JavaScript file into a module while still supporting wp_add_inline_script()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Below function will ensure that any scripts added using wp_add_inline_script() are not touched during the filtering process. | |
// We need to do this because the filte runs after the inline scripts have been concatenated: https://github.com/WordPress/WordPress/blob/6.1.1/wp-includes/class-wp-scripts.php#L406 | |
function make_scripts_modules( $tag, $handle, $src ) { | |
if ( 'your-script-handle' !== $handle ) { | |
return $tag; | |
} | |
$id = $handle . '-js'; | |
$parts = explode( '</script>', $tag ); // Break up our string | |
foreach ( $parts as $key => $part ) { | |
if ( false !== strpos( $part, $src ) ) { // Make sure we're only altering the tag for our module script. | |
$parts[ $key ] = '<script type="module" src="' . esc_url( $src ) . '" id="' . esc_attr( $id ) . '">'; | |
} | |
} | |
$tags = implode( '</script>', $parts ); // Bring everything back together | |
return $tags; | |
} | |
add_filter('script_loader_tag', 'make_scripts_modules' , 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment