The Right Way of Adding JavaScript to WordPress
I’ve written a post, Prevent JQuery From Conflict With Other Libraries, I mentioned that the right way to import JQuery to WordPress is using:
< ?php wp_enqueue_script(“jquery”); ? >
This will load the default JQuery coming with WordPress to your pages, the problem is what if you want a newer version of JQuery? WordPress doesn’t contain the latest version of JQuery, as they are not updating at the same time. But we can update JQuery for WordPress:
<?php
function my_init_method() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery'
, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
}
add_action('init', 'my_init_method');
?>
Put this into your function.php, it tells WordPress to use ‘http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js’ which is the latest version of JQuery as ‘jquery’ in this site. Very easy, isn’t it?
Another advantage to use wp_enqueue_script rather than directly use script tag is to prevent calling duplicate script. Some plugins, like Contact Form plugin, will call JQuery as well, if you use wp_enqueue_script, WordPress will not call JQuery twice.
wp_enqueue_script can be used to load customized javascript, this is an example of loading jquery.cycle.all.min.js which a slider plugin of JQuery:
<?php wp_enqueue_script('jquery.cycle.all.min','/wp-content/themes/mytheme/js/jquery.cycle.all.min.js?ver=2.9.2',array('jquery')); ?>
Notice that I add “?ver=2.9.2″ to the end of the link of the js file. 2.9.2 is the version of WordPress I am using. This is because that I found that WordPress will automatically add “?ver=2.9.2″ to the link, it turns out the link will be broken. After I added “?ver=2.9.2″ to wp_enqueue_script, everything become normal. I am not sure about the reason, wish someone can tell me.
The last parameter, array(‘jquery’), means this script is based on ‘jquery’, so that it will be loaded after JQuery.
If you are using wp_enqueue_script to load javascript, you have to put it above wp_head.
.
.




