我再次修改了答案,因为我最近注意到Twenty Twenty 开发人员使用script_loader_tag
要添加的挂钩async
和defer
到<script>
主题脚本的标记。
输入twentytwenty_theme_support()
在里面functions.php
, lines #139 & #140:
$loader = new TwentyTwenty_Script_Loader();
add_filter( \'script_loader_tag\', array( $loader, \'filter_script_loader_tag\' ), 10, 2 );
英寸twentytwenty_register_scripts()
在里面functions.php
, lines #208 & #209:wp_enqueue_script( \'twentytwenty-js\', get_template_directory_uri() . \'/assets/js/index.js\', array(), $theme_version, false );
wp_script_add_data( \'twentytwenty-js\', \'async\', true );
在TwentyTwenty_Script_Loader
class:public function filter_script_loader_tag( $tag, $handle ) {
foreach ( [ \'async\', \'defer\' ] as $attr ) {
if ( ! wp_scripts()->get_data( $handle, $attr ) ) {
continue;
}
...
}
return $tag;
}
因此,我想说/建议的是,您最好使用wp_script_add_data()
添加/注册自定义HTML属性(例如。async
) 并使用wp_scripts()->get_data()
检查<script>
标签应与自定义HTML属性一起添加,而无需手动指定句柄(例如wpfrank-ptbw-pinit-js
).下面是一个基于上述方法的示例,其中我使用wp_script_add_data( \'<handle>\', \'html_attrs\', [ list here ] )
. 此外,我正在使用PHP的DOMDocument
为了获得更精确的结果str_replace()
或preg_replace()
也可以。
add_action( \'wp_enqueue_scripts\', \'my_register_scripts\' );
function my_register_scripts() {
wp_enqueue_script( \'wpfrank-ptbw-pinit-js\', PTBW_PLUGIN_URL . \'assets/js/pinit.js\', array( \'jquery\' ), \'\', true );
wp_script_add_data( \'wpfrank-ptbw-pinit-js\', \'html_attrs\', [
\'async\' => \'async\',
\'defer\' => true,
\'data-pin-hover\' => \'true\',
] );
}
add_filter( \'script_loader_tag\', \'my_filter_script_loader_tag\', 10, 2 );
function my_filter_script_loader_tag( $tag, $handle ) {
$attrs = wp_scripts()->get_data( $handle, \'html_attrs\' );
// Bail if the script doesn\'t have any registered custom HTML attrs.
if ( empty( $attrs ) || ! is_array( $attrs ) ) {
return $tag;
}
$dom = new DOMDocument;
//$tag = mb_convert_encoding( $tag, \'HTML-ENTITIES\', \'UTF-8\' );
$dom->loadHTML( $tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$node = $dom->getElementsByTagName( \'script\' )[0];
foreach ( $attrs as $key => $value ) {
$node->setAttribute( $key, $value );
}
return $dom->saveHTML();
}