wp_enqueue_script_module()


WordPressのwp_enqueue_script_module()関数は、JavaScriptモジュールをエンキュー(登録)するために使用されます。この関数は、モジュールタイプのスクリプトを効率的に管理し、依存関係を解決するために役立ちます。

構文

wp_enqueue_script_module( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, array $args = array() );

引数の説明:

  • $handle(string) — スクリプトの識別子。ユニークである必要があります。
  • $src(string) — スクリプトのURL。省略可能です。
  • $deps(array) — このスクリプトが依存する他のスクリプトのハンドルの配列。
  • $ver(string|bool|null) — スクリプトのバージョン。キャッシュ対策に使用されます。
  • $args(array) — 追加の引数。例えば、array('type' => 'module')を指定できます。

例1: 基本的なモジュールのエンキュー

この例では、JavaScriptモジュールをエンキューします。

wp_enqueue_script_module('my-module', get_template_directory_uri() . '/js/my-module.js', array(), null, array('type' => 'module'));

例2: 依存関係のあるモジュールのエンキュー

この例では、依存関係を持つモジュールをエンキューします。

wp_enqueue_script_module('my-dependent-module', get_template_directory_uri() . '/js/my-dependent-module.js', array('my-module'), null, array('type' => 'module'));

例3: バージョン指定付きのモジュールのエンキュー

この例では、バージョンを指定してモジュールをエンキューします。

wp_enqueue_script_module('my-versioned-module', get_template_directory_uri() . '/js/my-versioned-module.js', array(), '1.0.0', array('type' => 'module'));

例4: インラインスクリプト付きのモジュールのエンキュー

この例では、インラインスクリプトを追加してモジュールをエンキューします。

wp_enqueue_script_module('my-inline-module', get_template_directory_uri() . '/js/my-inline-module.js', array(), null, array('type' => 'module'));
wp_add_inline_script('my-inline-module', 'console.log("Inline script loaded");');

例5: 条件付きモジュールのエンキュー

この例では、特定の条件でモジュールをエンキューします。

if (is_page('about')) {
    wp_enqueue_script_module('about-module', get_template_directory_uri() . '/js/about-module.js', array(), null, array('type' => 'module'));
}

例6: フッターでのモジュールのエンキュー

この例では、フッターでモジュールをエンキューします。

wp_enqueue_script_module('footer-module', get_template_directory_uri() . '/js/footer-module.js', array(), null, array('type' => 'module', 'in_footer' => true));

例7: 外部スクリプトのモジュールのエンキュー

この例では、外部のJavaScriptモジュールをエンキューします。

wp_enqueue_script_module('external-module', 'https://example.com/external-module.js', array(), null, array('type' => 'module'));

例8: 複数のモジュールを一度にエンキュー

この例では、複数のモジュールを一度にエンキューします。

wp_enqueue_script_module('module-one', get_template_directory_uri() . '/js/module-one.js', array(), null, array('type' => 'module'));
wp_enqueue_script_module('module-two', get_template_directory_uri() . '/js/module-two.js', array('module-one'), null, array('type' => 'module'));

注意点

  • モジュールタイプのスクリプトは、type="module"属性が必要です。
  • 依存関係を正しく設定しないと、スクリプトが正しく動作しない場合があります。
  • 外部スクリプトを使用する場合は、セキュリティに注意してください。

関連機能: