DiggingIntoWordPress

by Chris Coyier & Jeff Starr

Including jQuery in WordPress (The Right Way)

Posted by on

If you want, you can just download jQuery, put it on your server and link to it from your header.php file in the <head> section. But that can cause you grief. For one thing, some plugins use the jQuery library, and they are going to load it as well. This can cause problems. How was your plugin to know you already had it loaded?

Another thing is that WordPress already includes a copy of jQuery. Here is how you can load up jQuery in your theme the smart (and intended) way. Put the following code in your header.php file in the <head> section:

<?php wp_enqueue_script("jquery"); ?>

<?php wp_head(); ?>

Your theme probably already has the wp_head function, so just make sure you call the wp_enqueue_script function BEFORE that. Now you are all set to call your own jQuery JavaScript file, AFTER the wp_head function.

<script type="text/javascript"
   src="<?php bloginfo("template_url"); ?>/js/yourScript.js"></script>

You are ready to rock, but there are still some considerations. For example, safeguarding yourself from the future possibility of conflict with other libraries. You really shouldn’t be using multiple JS libraries to begin with, but… better safe than sorry.

To be super-safe, you can put jQuery into “no conflict” mode and use a different shortcut for jQuery. In this case “$j” instead of the default “$”. The standard “$”, for example, can conflict with Prototype. Here is an example of a safe bit of jQuery JavaScript:

var $j = jQuery.noConflict();

$j(function(){

    $j("#sidebar li a").hover(function(){
    	$j(this).stop().animate({
    		paddingLeft: "20px&"
    	}, 400);
    }, function() {
    	$j(this).stop().animate({
    		paddingLeft: 0
    	}, 400);
    });

});

Can you recognize this bit of code? We use it right here on Modern WordPress to do the cool “link nudging” in the sidebar!

48 Responses

  1. Seems there is a small problem in the code.

    The &quot; should be “"”.

    Still, useful post, thanks!

    • Thanks Marco, we are in the process of installing a code-escape plugin and some of the code got munged in the process. This should be fixed now. Cheers.

    • Yes, this is one of the reasons I hate to use to insert stuff.

      • Thare’s a plugin that replaces those codes and load the files from Google. I think it’s called Use Google Libraries.

        Combine that with this method and you have both a clean and fast way to load jquery and other js. :)

  2. Does the WordPress copy of jQuery reflect the current version available on jQuery’s site?

    • As of this writing, WordPress includes jQuery 1.3.2. Whenever jQuery comes out with a new stable version, WordPress adds it to the next update. More or less.

  3. Jeff, I believe that WP already puts its version of jQuery into no-conflict mode by default, as there is a legacy of using Prototype for WP in the past to think of.

    Otherwise, congrats on the launch of the site, and good luck with the self-publishing!

    • Thanks Matt, I have verified that WordPress does indeed use noConflict mode in its jQuery implementation. Thanks for pointing it out :)

  4. Daniele June 16, 2009

    For some reason this method doesn’t work for me. If I include jQuery with the script tag everything work as expected. This thing is driving me crazy :(

    • for some reason – mine won’t work with the wp_enqueue_script – but with the regular it does. any ideas?

  5. Good post, we need plugin developers to stop including their own so you end up having 6 instances of jquery being loaded on your WP sites…

    • I think the problem is usually on themes more than plugins :/

      If only it was possible to make WordPress itself check for any manual calls to jquery and other frameworks and replace them with wp_enqueue_script()..

  6. Isn’t it also a good idea to use the version google spreads, or the latest version via jquery instead of the own hosted jquery-instance. That way, if more sites use this method, the js-file gets cached and makes the page load faster ..

    grtz,
    Tom.

    • There’s a plugin for WordPress called “Use Google Libraries”. If you want to use that, do so. It’ll replace the references used by WordPress with the Google hosted versions.

      Using that plugin and doing the enqueue approach is the best way, because the enqueue approach takes care of dependencies, loads things in the correct order, and ensures that plugins and themes don’t conflict with each other by only loading each library once.

  7. Good idea, but it’s probably still better IMHO to load a minified version of jQuery and not the unpacked full source.

    I personally pull it from http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js and use a remove_acction() for those plugins that load it again. In all reality thought, I don’t use a lot of plugins that use jQuery other than the ones Envato commissions third parties for, or the ones I write myself. So I guess my situation is not cookie cutter.

    In any case, I can see this being useful though in situations where you might not have as much control as you like over jQuery being loaded in your theme.

    • WordPress uses the minified version of jQuery automatically, unless you have it set to “developer” mode, in which case it loads the full version.

      As for using Google libraries, there’s a plugin for that: “Use Google Libraries”.

  8. Nice to know, I hadn’t done this because I stick all my JS just before the closing body tag. If plugin authors were to insert their JS into the wp_footer tag area, we’d be onto a real winner performance-wise (YSlow).

    Thanks and good luck with this project!

  9. Stu | Selfconclusion.co.uk June 17, 2009

    Great article, I am going to start using these instead of uploading the same jQuery to each of my domains, thanks guys! Great site!

  10. Merrill June 20, 2009

    What about the various jquery plugins. Is there a proper way to load them in WordPress?

  11. Popper June 21, 2009

    What does template_url means? Plese can you give an example..

  12. oh wow – super useful post! i’ve been dreading doing this cos i thought it would take ages, but you’ve just made it so easy. :) thanks heaps!

  13. Great article and helped me solve numerous problems and conflicts. I was having an instance when I could not close a modal dialog in FF but in IE it worked fine.

  14. Ryan Kelly June 30, 2009

    WordPress’ wp_enqueue_script function can also load your own script for you that depends on jQuery, without making two calls to wp_enqueue_script. There is also a bool at the end that tells WordPress to load your script with the wp_head hook or the wp_footer hook. (In the example, the true as the last argument in wp_enqueue_scripts tells the script to load in the footer section. If you set this to false, it will load in the headers section.)

    Example: wp_enqueue_script(‘handle’, ‘path/to/js’, array(‘jquery’), ’1.0′, true);

  15. Ryan Kelly June 30, 2009

    Followup: You can also add other dependencies. If one dependency is already loaded (by a plugin, for example), wordpress will not load it twice.

    wp_enqueue_script(‘handle’, ‘path/to/js’, array(‘jquery’, ‘prototype’), ‘version’, false);

    will load your script “handle”, jQuery, and Prototype, all in the head section.

  16. You can also use the closure pattern to sandbox your code like this :

    (function($){
         $(function(){
              //your onload code
         });
    })(jQuery);

    It's totally safe and avoids breaking some plugins which rely only on the $ variable.

    Anyway, another good reason to use enqueue is it's much more easier to unqueue them remotely from a custom plugin/theme. I personnally removed them with hooks to unload some KB of display.

    Also, it's even better to make those scripts shrinked and minimized for faster responses.

    :-)

  17. Just what I needed. Thanks for this one!

  18. Has anybody had any problems with this? I have replaced my call to jquery with the method in this post and for some unknown reason it isn’t working.

    I’ve put the wp_enqueue call before the wp_head and my script.js after.

    When I look at the source code all of the scripts are in the right place but still no good. If I go back to my own copy of jquery it works again. Hmmm!

    I really want to use this method, its a lot cleaner and I love doing things the ‘right’ way.

    Anybody else ran into problems?

    • Remember when you include the internal version of jQuery that comes with WordPress this way, it’s in noConflict mode so your scripts won’t be able to use the “$” shortcut, which may be your problem, see the above article.

      If you’d rather not deal with this, you could link to a version of jQuery that isn’t in noConflict mode, such as linking to it from Google.

      Also, congrats on winning one of the prizes in the CSS-Tricks giveaway, did you get my email on that?

      • Hey Chris, thanks for the advice. I’ll look into it. I did receive your email, its the first time I’ve ever won anything, I’m well chuffed! Thanks buddy!

        I had a quick peek this morning but haven’t decided on anything just yet. I’ll take a look now and let you know.

      • Instead of linking to Google, better to wrap your $code into something like this:

        jQuery(document).ready(function($){
               // your $ based code here will work fine
        });

        Like so.

  19. This is great, gonna make it easier for me to do wordpress themes with jquery stuff, without making the user mess with getting jquery and all that.

    I’m bad at writing instructions, so anything that saves me from that, heh.

    Awesome tip.

  20. I have tried this trick every which way ! and it doesn’t work for me using WP 2.8.2:

    <script type="text/javascript"
    src="/js/myScript.js”>
    My theme just works like jQuery wasn’t loaded and checking with FF it looks like it is loaded !
    Any ideas why ? and how to make it work so I don’t load jQuery twice.(which works but slows loading pages )
    Thanks

  21. I have tried this trick every which way ! and it doesn’t work for me using WP 2.8.2 and your code exactly as advised above.
    My theme just works like jQuery wasn’t loaded and checking with FF it looks like it is loaded !
    Any ideas why ? and how to make it work so I don’t load jQuery twice.(which works but slows loading pages )
    Thanks

    • jean: If your jQuery code uses the $shortcode, wrap it in something like this:

      jQuery(document).ready(function($){
             // your $ code here
      });

      Then it’ll work.

  22. Thank you for the tips. They’ve gotten me part of the way there. But, like jean I have tried this every which way and just cannot get it to work. I am using it in a plugin and I understand from another blog that these techniques apply.

    The line in the plugin that was causing me problems is as follows:

    echo "\n";

    I commented it out and instead wrote:

    this solution solved the conflict problem, but now the plugin doesn’t work.

    Any help you could give me would be much appreciated. thanks.

    • I lied! the conflicts are still there and the plug in doesn’t work. Help! I’ve literally spent days trying to solve this.

  23. BeasleyQ August 11, 2009

    I am having a hard time loading jquery-ui-core and jquery-ui-tabs. Had no problems loading jquery, using:

    jQuery(document).ready(function($){
           // your $ based code here will work fine
    });

    to load the jflow plugin, but can’t get simple tabs to work in my theme. Anyone else have problems with wp_enqueue and jquery-ui-core?

    • BeasleyQ August 11, 2009

      hmmm. Well, I got it to work – love a fresh start on a new day. I am using the following:

      WP 2.7 – and using wp_enqueue to load jquery, jquery-ui-core, jquery-ui-tabs, and jflow. I had to load jquery first, since jflow depends on it. Loaded jflow Second, then loaded the ui-core and ui-tabs in that order. I swear i tried this a million times last night to no avail, but it seems happy now…

      I thought maybe the ordering was causing the problem – perhaps it was just a cache issue. Good luck all! Great blog by the way…

  24. I have also noticed that you can run a condtional statment on the function that imports

  25. <?php if(wp_enqueue_script('jquery')) {
           echo 'Works';
    } else {
           echo 'Failed';
    }
    ?>

  26. Trying to get it all to work with woothemes premium news. Seems like a bit of a nightmare! Have tried so many combos of whats suggested.

    Installing some plugins that call jquery break the theme.

    • I should mention I’m not very skilled with jquery or javascript :P. Can it be dumbed down any more for those like me? Like there are multiple references to jquery throughout the theme and some plugins, am I meant to replace them?

  27. I’m a bit confused about the no-conflict stuff. I know what the no-conflict function does, and I see what the enqueue WP function does. But what I don’t understand is what the end result of WP being in “no-conflict mode” by default is?

    If I set my no-conflict string to be $foo, then every time I want to use a jQuery function I should use $foo(function()). Yet before reading this article I had been using WP’s included jQuery (loaded with enqueue) and just $(function()).

    I guess the question is really this:

    If WP puts jQuery into no-conflict mode, what is the custom string I’m supposed to use?

  28. I am just experimenting with a new design, since the current one is a bit old (been using it the past 3 years). So far I hesitated to implement new themes and functions since I am really no expert when it comes to css, etc.
    I struggled quite some time to get jquery activated, but the adive in this post and in the post helped me out quite a bit!

    Thanks a lot!

    Myrddin

  29. v-render August 27, 2009

    wonderful and helpful information
    thank you so much !!!

Comments are closed. Contact us with any critical information. Thank you!

Code is poetry