第四轮那个汉堡菜单需要一段 JS。很多人直接在 footer.php 里塞一个 <script>,能跑,但别这么干。
把 JS 存成 js/main.js,然后在 functions.php 里:
function itheme_scripts() {
wp_enqueue_script(
'itheme-main',
get_template_directory_uri() . '/js/main.js',
array(),
'1.0',
true // 第五个参数 true = 放到 </body> 之前
);
}
add_action( 'wp_enqueue_scripts', 'itheme_scripts' );
传 true,脚本会被放到 </body> 之前。这样浏览器先渲染页面、再执行脚本,页面不会「先是白的,然后才出来」。
传 false(或不传),脚本进 <head>,会阻塞渲染——页面得等它下载执行完才显示。
第三个参数 array() 是「要等谁先加载」。如果你的脚本依赖 jQuery,就写 array( 'jquery' ),WordPress 会保证 jQuery 先加载,你不用手写 <script src="jquery...">。
如果你的脚本不需要在解析过程中改 DOM,可以用 wp_script_add_data( 'itheme-main', 'defer', true ) 再推迟一点执行。但对一个汉堡菜单来说,放到 body 末尾已经够了。
下一篇:把写死的 title 换掉。
本系列:迭代式建主题 · 目录(72 篇) | 上一篇 (49) | 下一篇 (51)