从CDN为WordPress调用jQuery

WordPress的主题和插件大量地使用了jQuery。把jQuery库缓存到CDN上面,或者用户在自己的浏览器缓存里已经有了jQuery库,就能在一定程度上加速Wordpress的载入速度。Goolge提供的jQuery库是放在Google自己的CDN,另外有一个MiniCDN将jQuery库缓存到国外的亚马逊和国内的盛大云等等几个CDN,所以对国内来说,MiniCDN更好用一些。

有两种方法加载CDN上的jQuery

1. 在主题的Header里面加载(Wordpress官方并不推荐)

在主题的header.php的<header>标签里面加上下面几行


<!--MiniCDN-->
<script type="text/javascript" src="http://c1.minicdn.com/google/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">window.jQuery || document.write('<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/jquery.min.js">\x3C/script>')</script>
<!--/MiniCDN-->

2. 在functions.php里面加载(官方提供的方法,但是我试过会导致网站访问不正常,但是安装一个叫做WP jQuery CDN的插件,里面是使用同样的方法,却是可以正常工作的。我目前是使用这个插件加上自己修改成MiniCDN的URL来工作的,效果还不错。)

//Making jQuery Google API in MiniCDN
function my_scripts_method() {
if (!is_admin()){
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://c1.minicdn.com/google/ajax/libs/jquery/1.7.1/jquery.min.js');
wp_enqueue_script( 'jquery' );
}
}

add_action(‘wp_enqueue_scripts‘, ‘my_scripts_method’);

这里要注意:很多文章介绍在add_action里面使用’init‘,但是会导致一些问题,官方提示“by using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.”

3. 使用”Use Google Libraries“插件(官方推荐,但是无法使用其他CDN上的jQuery库)

 

 Reference

http://codex.wordpress.org/Function_Reference/wp_enqueue_script

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

Back to Top