您始终可以通过添加defer 属性来修改<script> 标记的输出。这将使您的(JS)脚本非阻塞。
具有 defer 属性的脚本将阻止 DOMContentLoaded 事件触发,直到脚本加载并完成评估。 MDN
首先将wp_enqueue_script 和wp_enqueue_style 包装在wp_enqueue_scripts 操作处理程序中。这是注册和排队脚本和样式WP Docs的正确方法。
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('jqm_js', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.js', ['jquery'], '1.2.0');
wp_register_style('jqm_css', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.css', [], '1.2.0');
wp_enqueue_style('jqm_css',);
}, 10);
使用script_loader_tag 过滤器,您可以修改<script> 标记的生成方式。如果句柄在$handles 数组中,则以下 sn-p 将检查每个已注册和排队的脚本。如果是,那么它将在脚本中添加一个defer 属性。
修改 $handles 数组中的值以添加或删除您想要延迟的任何脚本。
add_filter('script_loader_tag', function ($tag, $handle, $src) {
$handles = ['jqm_js'];
if (in_array($handle, $handles)) {
$tag = str_replace(' src', ' defer="defer" src', $tag);
}
return $tag;
}, 10, 3);