How to Link External jQuery/Javascript files with WordPress

So I’m using Starkers to base my next WP theme on and I’ve run into a small issue, I was including my own version of jQuery in the header.php file but when inspecting my site using Firebug I noticed jquery was being downloaded twice, I did a bit of digging and noticed that not only was I including the file but so was the wp_head() function.

In trying to fix the problem I noticed a comment in the header file, of which originated came from the Twenty Ten theme:

/* Always have wp_head() just before the closing </head>
 * tag of your theme, or you will break many plugins, which
 * generally use this hook to add elements to <head>, such 
 * as styles, scripts, and meta tags
 */

So here’s my problem, I am under the impression that the jQuery file has to be set before any other file that wants to use it and that wp_head() should be the last thing in the <head> element, I’m slightly confused now as I’m wondering should I put wp_head() at the top so the WP included jQuery file will be used for all my plugins, even though it says not to do so.

I did comment out the jQuery line in the wp_head() function but it’s required for the admin page so I had to put it back.

I’d also like to use (at least experiment) with using the Google CDN version of jQuery, but don’t want to include it twice!

I hope you understand what I’m trying to explain, any suggestions on how I can solve this problem would be most appreciated. I’d also appreciate any advice on how you handle your JavaScript files with the header file.

Thanks!

3

From the wording of your question, you must be adding scripts by writing <script> tags in your template. Add your own scripts via wp_enqueue_script() in your template’s functions.php, appropriately setting dependences on jQuery, and wp_head() will add the scripts for you.

function my_scripts() {
    wp_enqueue_script( 'my-sweet-script', get_bloginfo('template_directory') . '/script.js', array('jquery') );
}
add_action('template_redirect', 'my_scripts');

See the codex page for more info.

Leave a Comment