WordPress网站如何将JavaScript从head移到footer

JavaScript是一个客户端脚本语言,它的执行是由浏览器完成的。JavaScript一般放在head部分和footer部分。在这篇文章中,我将展示如何将WordPress网站的JavaScript脚本从head移到footer。

为什么要将JavaScript移到footer

很简单,将JavaScript移到footer可以提升网页的加载速度。JavaScript有一个特点叫做“阻止渲染”。如果JavaScript放置在网页的head部分,那么在加载网页的时候,首先要加载JavaScript。这些head部分的JavaScript在加载完成之前,网页中的其他元素是不可以同时加载的。这就叫做“阻止渲染”(render blocking)。所以,我们最好要将JavaScript放置在网页的底部。这样网页的文字、图片等其他元素可以先呈现在浏览者面前,然后JavaScript在后台加载。

如何将JavaScript移到footer

步骤非常简单。打开WordPress主题文件夹下面的functions.php文件,在文件末尾添加下面的代码。

// Custom Scripting to Move JavaScript from the Head to the Footer
function remove_head_scripts() { 
 remove_action('wp_head', 'wp_print_scripts'); 
 remove_action('wp_head', 'wp_print_head_scripts', 9); 
 remove_action('wp_head', 'wp_enqueue_scripts', 1);
 add_action('wp_footer', 'wp_print_scripts', 5);
 add_action('wp_footer', 'wp_enqueue_scripts', 5);
 add_action('wp_footer', 'wp_print_head_scripts', 5); 
} 
add_action( 'wp_enqueue_scripts', 'remove_head_scripts' );
// END Custom Scripting to Move JavaScript

保存文件后,重新加载网页。通过查看网页的源码可以发现,所有的JavaScript都移到了网页的底部。确保你的网页可以在桌面和手机端正常显示。我们可以在mobiletest.me上看看网页在不同的移动设备上是如何显示的。

并不是所有的WordPress网站都可以用这种方法。有的WordPress主题有一个slideshow,这些slideshow要求jQuery和JavaScript在head部分中首先加载。如果使用上面的方法后,slideshow不能正常显示,那么把上面的代码从functions.php文件中删除。我们可以用另外一种方法。

为这篇文章评分
[Total: 1 Average: 5]

Leave a Reply

Your email address will not be published.

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here