这个script_loader_tag
版本4.1中添加的过滤器解决了此问题。要向排队脚本添加异步属性,可以执行以下操作:
/**
* Add an aysnc attribute to an enqueued script
*
* @param string $tag Tag for the enqueued script.
* @param string $handle The script\'s registered handle.
* @return string Script tag for the enqueued script
*/
function namespace_async_scripts( $tag, $handle ) {
// Just return the tag normally if this isn\'t one we want to async
if ( \'your-script-handle\' !== $handle ) {
return $tag;
}
return str_replace( \' src\', \' async src\', $tag );
}
add_filter( \'script_loader_tag\', \'namespace_async_scripts\', 10, 2 );
如果要向脚本添加id,可以在
str_replace()
也
更多信息可通过文章获取»Add Defer & Async Attributes to WordPress Scripts«由Matthew Horne和开发商参考script_loader_tag
.