Skip to content

Instantly share code, notes, and snippets.

@UVLabs
Last active January 23, 2023 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UVLabs/51a3258257923c7e35037eff5f71e20c to your computer and use it in GitHub Desktop.
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()
<?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