如何让WordPress的script_loader_tag成功添加type="module"属性?
问题排查与修正方案
你的代码存在三个核心问题,导致type="module"属性无法正常添加:
1. 脚本Handle重复且过滤器匹配对象错误
你给两个入队脚本使用了相同的js-file作为Handle,WordPress会自动覆盖重复的Handle,最终只会加载最后一个符合条件的脚本。同时,script_loader_tag过滤器中你错误地将注册脚本的函数名(notation_page_js/notation_home_js)作为匹配对象,而实际上应该匹配脚本的唯一标识Handle。
2. 条件判断语法错误
if ( 'notation_page_js || notation_home_js' === $handle ) 是无效逻辑:你将包含运算符的字符串与$handle做全等比较,这永远不会成立,正确写法应该是判断$handle是否属于目标Handle数组。
修正后的完整代码
// Load RoughNotation page title animations function notation_page_js() { if( !is_page('2') ) { // 使用唯一Handle:rn-page-script wp_enqueue_script( 'rn-page-script', get_stylesheet_directory_uri() . '/js/rn-page.js', array(), false, true ); } } add_action('wp_enqueue_scripts', 'notation_page_js'); // Load RoughNotation home hero animation function notation_home_js() { if( is_page('2') ) { // 使用唯一Handle:rn-home-script wp_enqueue_script( 'rn-home-script', get_stylesheet_directory_uri() . '/js/rn-home.js', array(), false, true ); } } add_action('wp_enqueue_scripts', 'notation_home_js'); // Add module type to RoughNotation script tags function add_type_attribute($tag, $handle, $src) { // 匹配两个脚本的唯一Handle $module_scripts = array('rn-page-script', 'rn-home-script'); if ( in_array($handle, $module_scripts) ) { // 替换原有标签,添加type="module"属性 $tag = str_replace( '<script', '<script type="module"', $tag ); } return $tag; } add_filter('script_loader_tag', 'add_type_attribute' , 10, 3);
额外优化说明
- 给
wp_enqueue_script添加最后一个参数true,将脚本放在页面底部加载,优化页面渲染性能; - 使用
str_replace修改原有标签,比直接重写更安全,保留WordPress自动添加的版本号、加载位置等属性; - 用数组存储目标Handle,方便后续扩展更多需要添加
type="module"的脚本。
内容的提问来源于stack exchange,提问作者carbonrich
相关产品推荐
相关产品推荐

