wp enqueue script – How to load javascript module with script_loader_tag hook?

defined('TEST_JS_DIR') or define('TEST_JS_DIR',plugin_dir_url(__FILE__).'js');
if(!class_exists('plugin_test'))
{
  final class plugin_test
  {
    public function __construct()
    {
      add_shortcode('environ_test',array($this,'content_to_render'));
      add_action('wp_enqueue_scripts',array($this,'register_scripts'));
      add_filter('script_loader_tag', array($this,'add_type_attribute'));
    }
    public function add_type_attribute($tag, $handle, $src) {
      if ( 'test_script' !== $handle || 'test_script2' !==$handle ) {
          return $tag;
      }
      // change the script tag by adding type="module" and return it.
      $tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
      return $tag;
    }
    public function register_scripts()
    {
      wp_enqueue_script('test_script',TEST_JS_DIR.'/testfront.js',array('jquery'));
      wp_enqueue_script('test_script2',TEST_JS_DIR.'/testback.js',array('jquery'));
    }
    public function content_to_render($atts)
    {
      $test="<p>dont mind me</p>";
      return $test;
    }
  }
  new plugin_test();
}

When $priority And $accepted_args is not passed script_loader_tag Hook, I get the error:

Uncaught ArgumentCountError: Too few arguments to function plugin_test::add_type_attribute()

But when they are passed like this:

add_filter('script_loader_tag', array($this,'add_type_attribute'),10,3)

I don’t get any errors but my script types don’t change type="module", don’t hook script_loader_tag arguments must be passed ( $tag, $handle, $src ) by default? Is there something wrong with my method of converting the script type to module?

Leave a Comment