# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: javascript, modules, performance
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-script-module-example/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Load a JavaScript Module Only Where It Is Needed" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
