Load a JavaScript Module Only Where It Is Needed
Registers a native JavaScript module with WordPress's Script Modules API and loads it only on pages that contain a chosen block, so modern ES module code needs no bundler and costs nothing elsewhere.
Opens WPIDE on
Code
// Module URL and the block that needs it.
$wpide_module_url = content_url( 'js/site.js' );
$wpide_module_block = 'core/gallery';
add_action( 'init', function () use ( $wpide_module_url ) {
if ( function_exists( 'wp_register_script_module' ) ) {
wp_register_script_module( 'wpide/site', $wpide_module_url, array(), '1.0' );
}
} );
add_filter( 'render_block_' . $wpide_module_block, function ( $content ) {
if ( function_exists( 'wp_enqueue_script_module' ) ) {
wp_enqueue_script_module( 'wpide/site' );
}
return $content;
} );
Notes
Needs WordPress 6.5+; put your module file at wp-content/js/site.js (or change $wpide_module_url) and set the block that triggers it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.