LoginSignup
1
0

はじめに

wp_enqueue_scriptを使うと、scriptタグの書式が固定されてしまいます。
type=module/async/deferなどを追加する方法を解説します。

解決方法

下記をfunctions.phpに追記しましょう。
下記の例だと、hogeとpiyoのみmoduleで読み込むことができます。
スクリプトタグの修正箇所にasyncなどの文字列を追加して、別のパラメーターを付与することもできます。

functions.php

// スクリプト読み込み
wp_enqueue_script('hoge', __DIR__ . 'js/hoge.js', [], '1.0.0', true);
wp_enqueue_script('fuga', __DIR__ . 'js/fuga.js', [], '1.0.0', true);
wp_enqueue_script('piyo', __DIR__ . 'js/piyo.js', [], '1.0.0', true);

function add_type_attribute($tag, $handle, $src)
{
    $target_handler = ['hoge', 'piyo'];
    if (!in_array($handle, $target_handler)) return $tag;
    
    $tag = '<script type="module" src="' . esc_url($src) . '"></script>';
    return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute', 10, 3);

実際の使用事例

実際にはプラグイン上で使用しました。

plugin.php

function store_list_callback($atts)
{
    wp_enqueue_script(
        'store_list_js',
        plugin_dir_url(__FILE__) . 'js/common/main.js',
        [],
        '1.0.0',
        true
    );
    
    // ~その他の処理~

}
add_shortcode('store_list', 'store_list_callback');

function add_type_attribute($tag, $handle, $src)
{
    $target_handler = ['store_list_js'];
    if (!in_array($handle, $target_handler)) return $tag;
    
    $tag = '<script type="module" src="' . esc_url($src) . '"></script>';
    return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute', 10, 3);

ショートコードを展開するためのプラグインで、ショートコードに対してスクリプトを読み込みたいと思いました。
ショートコードを使う記事内でスクリプトを毎回読み込むのが手間なので。

こうすることで、別メディアに対して同じ機能を実装したい場合、プラグインの載せ替えだけで対応できるようになりました。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0