如何延迟WordPress block.json脚本?解决句柄不被识别问题
解决@wordpress/scripts块脚本无法添加defer属性的问题
问题根源
你在block.json里的script数组写法有误:["file:./counters.js", "counters_js"]并不是把本地脚本注册为counters_js句柄,而是将counters_js作为该脚本的依赖项。WordPress会自动为file:./counters.js生成格式为block-{块名}的句柄(比如你的块名是myproject/counters,自动句柄就是block-myproject-counters),这就是你的过滤器找不到counters_js的核心原因。
解决方案
方案1:使用自动生成的句柄添加defer
直接用WordPress为本地脚本生成的默认句柄修改标签:
if ( !is_admin() ) add_filter( 'script_loader_tag', 'lr_defer_scripts', 10, 3 ); function lr_defer_scripts( $tag, $handle, $src ) { // 替换成你的块自动生成的句柄 $defer_scripts = array( 'block-myproject-counters' ); if ( in_array( $handle, $defer_scripts ) ) { // 在原有script标签中插入defer属性,保留所有默认属性 return str_replace( '<script ', '<script defer ', $tag ); } return $tag; }
方案2:手动注册脚本句柄
如果想自定义句柄,先手动注册脚本,再在block.json中引用:
- 在主题/插件的
functions.php中注册脚本:
function lr_register_block_scripts() { if ( !is_admin() ) { wp_register_script( 'counters_js', // 替换为你的脚本实际路径 get_template_directory_uri() . '/path/to/counters.js', array( 'wp-element' ), // 根据脚本实际依赖调整 // 用文件修改时间作为版本号,避免缓存问题 filemtime( get_template_directory() . '/path/to/counters.js' ), false // 设为true可将脚本加载在页脚,配合defer效果更优 ); } } add_action( 'wp_enqueue_scripts', 'lr_register_block_scripts' );
- 修改
block.json的script字段,只引用注册好的句柄:
{ "name": "myproject/counters", "title": "Counters", "description": "Blocco counters", "keywords": ["counters", "counter"], "style": [ "file:./counters.css", "counters_style" ], "script": [ "counters_js" ], "align": "full" }
此时你的原过滤器就能正常识别counters_js句柄了。
方案3:针对前端脚本使用viewScript
如果你的脚本只需要在前端(非编辑器)加载,推荐用viewScript替代script,它的自动句柄格式为view-block-{块名}:
{ "name": "myproject/counters", "title": "Counters", "description": "Blocco counters", "keywords": ["counters", "counter"], "style": [ "file:./counters.css", "counters_style" ], "viewScript": "file:./counters.js", "align": "full" }
然后过滤器中使用view-block-myproject-counters作为句柄即可。
内容的提问来源于stack exchange,提问作者Luca Reghellin
相关产品推荐
相关产品推荐

