WordPress调用jQuery库的4种方法:老大网络 www.yulaoda.com

在WP中需要使用到jQuery的地方太多了,我们还是从基本的层面入手研究下吧。

不知WP从哪一个版本开始默认加载jQuery库,jquery.js在2.8以前才30k现在是56k,jQuery的JS文件放在head处,多多少少会影响到WP的打开速度,把它放在footer处?有时会影响到插件的运行。所以产生很多插件通过Google API替换了WP默认的jQuery,利用谷歌强大的服务器来加快其调用加载速度。

WP 的 jQuery 和原版唯一的不同, 就是在最后一行加了 jQuery.noConflict();
这个noConflict() 就是为了与其它的library 兼容性, 如:Prototype, MooTools, 或 YUI.
相关内容请参考: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

下面是调用jQuery的几种方法:

1.自己从网上下载挂在自己网站中。

<script type=”text/javascript” src=”<?php bloginfo(‘template_directory’); ?>/js/jquery.js”>
</script>

2.直接调用谷歌 Google 的 API库

<scrip和type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js”>
</script>

3.直接调用WP自带的  jQuery

<?php wp_enqueue_script(‘jquery’); ?>

但要注意的是: wp_enqueue_script(‘jquery’); 必需加在 wp_head(); 的前面,

而且 js 的写法是:

jQuery(document).ready(function($) {
// $() will work as an alias for jQuery() inside of this function
});

这样 jQuery() 包里的所有 $() 才能被正确识别.
大家的习惯写法也:

$(document).ready(function() { … }); 需要改为 jQuery(document).ready(function($) { … });
这是为了 noConflict();

另外, 把全部简写的“$” 还原回,使用“jQuery” 也行.