WP 提速之按需合并压缩 JS 文件

好久没有优化 WordPress 了,手又开始痒痒了,早上一醒来就踏上了我计划一晚上的 WordPress 加速之旅。本次提速的主题是按需合并压缩 JS 文件,本文是建立在合并与压缩 JS 文件的基础之上的,如果有童鞋不明白如何合并与压缩 JS 文件,可以先看看以下两篇文章:《合并JS文件两步走》《Wordpress之终极Gzip兼容IE6》。解决了合并与压缩 JS 的问题,我们再来看看何为按需?怎么个按需法?

之前,我不分清红皂白地将所有的 JS 文件一股脑地全部压缩在一个 all.js 文件中,再用 gzip 压缩这个文件,这个方法当然没错,但不是最好的,因为每个页面需要调用的 JS 不都一样,如果我们强制一些不需要所有 JS 文件的页面也加载整个 all.js,那岂不是浪费资源拖慢速度?

我解决这个问题的方法是给每个页面定义不同的 JS 文件,然后用 PHP 的判断句来按需调用这些 JS 文件。基本语句格式如下:

<?php if (is_home()) { ?>
<script src="1.js文件的地址" type="text/javascript" charset="utf-8"></script>
<?php } elseif( is_single() ) { ?>
<script src="2.js文件的地址" type="text/javascript" charset="utf-8"></script>
<?php } elseif( is_page() or is_category() or is_tag() or is_search() or is_day() or is_month() or is_year()) { ?>
<script src="3.js文件的地址" type="text/javascript" charset="utf-8"></script>
<?php } ?>

代码仅作参考,具体还要根据每个主题的需要修改。效果可以见我的友情链接页面,现在仅仅加载了0.9K的 JS,如果换作之前,这么一个简单的页面也需要加载20K的 JS,太无辜了。修改后提速的效果还是很明显的。Have a try 吧!

,,

相关的文章
    • 呵呵,谢谢,就是加了个滤镜而已,之前写过一篇相关的文章,喜欢的话你也可以试试:http://www.life-studio.cn/page-transitions-in-ie.html

  1. Pingback: 小站提速手记之 —— 按需加载 CSS | 木木木木木

  2. 再次被我捕捉到了。。回复后就出来这个提示:
    Warning: Cannot modify header information - headers already sent by (output started at /www/users/life-studio.cn/wp-content/plugins/clean-archives-reloaded/clean-archives-reloaded.php:1) in /www/users/life-studio.cn/wp-comments-post.php on line 82

    Warning: Cannot modify header information - headers already sent by (output started at /www/users/life-studio.cn/wp-content/plugins/clean-archives-reloaded/clean-archives-reloaded.php:1) in /www/users/life-studio.cn/wp-comments-post.php on line 83

    Warning: Cannot modify header information - headers already sent by (output started at /www/users/life-studio.cn/wp-content/plugins/clean-archives-reloaded/clean-archives-reloaded.php:1) in /www/users/life-studio.cn/wp-comments-post.php on line 84

    Warning: Cannot modify header information - headers already sent by (output started at /www/users/life-studio.cn/wp-content/plugins/clean-archives-reloaded/clean-archives-reloaded.php:1) in /www/users/life-studio.cn/wp-includes/pluggable.php on line 865