Much has been said on the subject of properly registering and enqueueing scripts in WordPress, so I hate to write yet another “including jQuery in WordPress the right way” post, so I’ll attempt to cover it from a different angle.

Because jQuery ships with WordPress, it’s really just a simple matter of making sure you call:

wp_enqueue_script( 'jquery' );

In your functions.php file.

But that’s really only half of it. After that, you have a matter of actually setting up your JavaScript source.

I’m assuming that you have a file named theme.js and that it’s being enqueued just after the jQuery enqueue so that your functions file looks like this:

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/theme.js' );

After that, it’s important to make sure that you’re properly setting up the JavaScript file itself.

jQuery in WordPress The Right Way

If you look around the web, you’re like to see several ways of doing this.

Using jQuery.noConflict

One way that developers like to make sure they aren’t interferring with other scripts is by taking advantage of the jQuery.noConflict method.

The advantage to doing this is that it relinquishes the $ function so that you can use whatever variable you want to represent jQuery, but the problem is that developers don’t often restore the variable at the end of their script thus potentially breaking any script that’s included after it.

Using The $.ready Function

Using the $.ready function is actually supposed to be used whenever we want to fire a function as soon as the DOM is loaded. The thing is, a lot of developers actually use this in several ways.

One way is by doing this:

$(document).ready(function () {
  /* Code here */
});

A second way is by doing this:

$(function () {
  /* Code here */
});

But there’s a problem with doing this: It assumes that the jQuery function hasn’t been relinqushed by using the noConflict method demonstrated above.

The Anonymous Function Call

When you’re working with jQuery and WordPress, there are two things that can be guaranteed: WordPress has it included and you can access it via the original jQuery function.

To be complete, you can enqueue your theme JavaScript by making sure jQuery is enqueued first:

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/theme.js', array( 'jquery' ) );

From here, all other JavaScript-strategies are off the table. Simply stub the file out like this:

;(function ($) {

   // Example of how to call the $.ready function
   $(function () {

   });

}(jQuery));

The first semicolon guarantees that all other JavaScripts will be properly terminated prior to invoking your own function. Technically, this point could be argued but that’s outside the scope of this post.

Secondly, this method guaranteed that you’ll have access to the $ as jQuery is passed as an argument into the anonymous function and then referenced by $.

Finally, the anonymous function will not cause conflicts with any other plugins, libraries, or scripts as it’s fully encapsulated.

Category:
Tips
Tags:
,

Join the conversation! 8 Comments

  1. When using this statement:
    wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/theme.js', array( 'jquery' ) );
    with jQuery as a dependency ( `array( ‘jquery’ )` ) doesn’t WordPress enqueue it for you?

    • Honestly, I’ve always been as explicit as possible. It’s my understanding that it waits until the dependency is laoded to load said script.

      From the Codex:

      Array of handles of any script that this script depends on (scripts that must be loaded before this script). false if there are no dependencies. This parameter is only required when WordPress does not already know about this script.

      • I posed the question as a discussion point (*grin*) as I generally rely on the dependency argument to insure jQuery is loaded; in most instances WordPress will have already loaded jQuery before the plugin/theme is initialized.

        In cases where jQuery has not been loaded before the dependency call, WordPress will load the jQuery library that comes with WordPress since the library is considered to be a “known” one.

        • I posed the question as a discussion point (*grin*)

          I applaud you for this ;).

          But in all seriousness – I’m obviously with you. I’ve had enough experiences during development with plugins and with building themes with which others use a ton of plugins to know that being explicit about including jQuery has just been the safer route.

    • Yes, this is exactly what the dependency argument is for. You can explicitly enqueue jQuery on a line before you enqueue your script, but if you have multiple functions enqueueing multiple scripts in various situations this becomes redundant. The script won’t be loaded more than once no matter how you enqueue it, so long as you use some form of wp_enqueue_script() and don’t try a hacky solution of printing the script tags directly.

      • The way WordPress manages the script importing is nice so that you don’t run into situations where you’re importing a script twice, but I’ve hit snags in other work where some plugin or third-party script deregistered something and having it explicitly loaded and set as a dependency has helped mitigate this problem.

        Sure, it’s not a very common problem but it’s significant enough to where I lean into the side of caution rather than assume too much about what third-party tools I may be dealing with down the line.

    • Yes, I personally prefer to use jQuery as a dependency, rather than enqueuing it separately.

      That’s mainly because my thinking goes, “I want to enqueue myscript.js”, “myscript.js needs jQuery”. Therefore when I enqueue myscript.js, I’ll list jQuery as a dependency. It’s not that I want to enqueue jQuery, I want myscript.js!

      Does that make sense?

      Ultimately, I don’t think it matters a jot. All the scripts are added to an array and then the HTML is generated. How you got them into the array (assuming you’re using provided functions) ends up being irrelevant.

      I can see how enqueuing jQuery separately first might make your code more readable to others, potentially though.

      • Aside from the readability argument, I’ve also covered my main reasons for doing it like I’ve stated above in some other comments.

        You could probably argue that we’re splitting hairs at this point, but I tend to be pretty conservative (read: explicit) when it comes to importing my scripts just to prevent any unintended consequences.

        Usually, when someone contacts me with a bug around JavaScript, this helps me know and/or eliminate that it’s mine since I know how I included stuff in the first place ;).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.