Thursday, October 20, 2022
HomeWordPress Developmentwp enqueue script - load JavaScript modules with script_loader_tag hook?

wp enqueue script – load JavaScript modules with script_loader_tag hook?


outlined('TEST_JS_DIR') or outline('TEST_JS_DIR',plugin_dir_url(__FILE__).'js');
if(!class_exists('plugin_test'))
{
  last class plugin_test
  {
    public perform __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 perform add_type_attribute($tag, $deal with, $src) {
      if ( 'test_script' !== $deal with || 'test_script2' !==$deal with ) {
          return $tag;
      }
      // change the script tag by including kind="module" and return it.
      $tag = '<script kind="module" src="' . esc_url( $src ) . '"></script>';
      return $tag;
    }
    public perform 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 perform content_to_render($atts)
    {
      $check="<p>dont thoughts me</p>";
      return $check;
    }
  }
  new plugin_test();
}

When $precedence and $accepted_args are usually not handed to the script_loader_tag hook, I get the error:

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

However when they’re handed like so:

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

I get no error however my script varieties do not change to kind="module". Is not the hook script_loader_tag speculated to go the arguments ( $tag, $deal with, $src ) by default? Is there one thing fallacious with my methodology to alter the script kind to module?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments