JavaScript for WordPress Developers: Loading JavaScript in WordPress

JavaScript for WordPress Developers: Loading JavaScript in WordPress

Over the past three weeks, we’ve looked at how to get started using JavaScript on your website, how to implement jQuery for animations and effects, and how to use JavaScript objects as part of this series.

Now we’re going back to basics. In order to actually use JavaScript, you need to know how to load it onto your site.

This is the fourth post in our five-part series focusing on JavaScript for WordPress developers. Throughout this series, you’ll learn the basics, but I’ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about WordPress Development for Beginners.

So far in this series we’ve looked at the basics of JavaScript, variables, arrays, functions, objects and we’ve sunk our teeth into basic jQuery. Now it’s time to dig a little deeper and start to understand how jQuery fits together with WordPress and how you can load scripts while maintaining their dependencies.

Missed a tutorial in our JavaScript for WordPress Developers series? You can catch up on all five posts here:

How WordPress Loads Scripts

Let’s take a step back and first look at how WordPress loads scripts and styles. We’ve learned that when creating JavaScript files you can add them to your page in the head section or in the body section, preferably at the bottom.

WordPress does the exact same thing but you can’t (read: shouldn’t) just plop these script tags in the header or footer file of your theme. WordPress uses an intelligent loading mechanism called enqueueing that figures out which files to load and when.

This mechanism is needed to make sense of dependencies. If you write some jQuery code for your theme, jQuery itself needs to be loaded first. You may write code that relies on a jQuery plugin. In this case, jQuery must be loaded first, then the plugin, and then your code.

Enqueueing Scripts

You can enqueue scripts in your theme’s functions file or in a plugin file. Here’s the full code for including a script that relies on jQuery:

Firstly, a function must be hooked into WordPress. The first argument of the add_action() function tells WordPress where these scripts should be placed: in the front-end of the website or in the admin. If you use wp_enqueue_scripts they will be placed on the user-facing side, if you use admin_enqueue_scripts they will be placed in the admin.

Within the hooked function you can use wp_enqueue_script to add the scripts you need. The function takes one required and four optional parameters:

  1. The first parameter is the name of your script. You can choose any you like but make sure to name it something unique to prevent naming issues.
  2. The second parameter should contain the location of the script file.
  3. The third parameter contains an array of dependencies. In the example above I’ve indicated that jQuery is a dependency. All dependencies are loaded before the script.
  4. The fourth parameter is a version number
  5. The fifth and final parameter indicates whether you want to load the script in the header or at the very end of the body section. Use true to load at the end, or false (or omit the value) to load it in the head section.

Dependencies

WordPress ships with a copy of jQuery, which is why you can add it as a dependency without any hassle. There are a great many other scripts and jQuery plugins WordPress contains. If your code depends on any of them don’t include your own copy, just add it as a dependency. See this script list in the WordPress Codex to see which ones you can use.

If you are including multiple scripts of your own making you can add them as dependencies just the same. Take a look at the example below:

Note that since the base script depends on jQuery the extension script depends on it as well. Regardless, you do not need to add jQuery as a dependency for both. This makes script management a lot easier!

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

Registering & Enqueueing

Adding a script actually consists of two steps but if you use the wp_enqueue_script() as shown it is condensed into one. In reality, the first is registered with WordPress, which means that WordPress will “know” about the script. The second step is enqueueing when it is actually added to the page.

In some cases you may want to do them separately to ensure efficient loading of scripts. I’ll show you some neat use-cases shortly.

To register and enqueue in two steps simply use the wp_register_script() with the exact same parameters as you used wp_enqueue_script(), then use wp_enqueue_script() with a single parameter, the script name (sometimes called the handle.)

If you’re registering and enqueueing in the same place it doesn’t really make sense but as you’ll see in a moment, sometimes you can register in one function and enqueue in another.

Conditional Loading

Sometimes you’ll want to use your script on every single page but often you only need it in specific places. This is especially true when creating scripts for the admin. A good example is the use of shortcodes. Shortcodes enable users to create advanced displays in the content editor using a few simple tricks.

For example, you could build an image carousel which users could add to the post like this: [carousel ids='42,124,123,331,90']. A carousel would be created on the post’s page using the images designated by the ids. To make this happen you would create carousel.js which relies on jQuery. Here’s some code to make this happen (it won’t actually make the carousel just demonstrate script loading):

We registered the script to make sure WordPress knows about it, but we only enqueue it within the shortcode function itself. This way the script is only added to the page if the shortcode is used on the page. Neat-o!

Another method to load scripts conditionally is the use of conditional functions. If you want to load a script on all category archive pages you could use the is_category() conditional tag.

The WordPress Codex entry on admin_enqueue_scripts offers a great example of how to target scripts to specific admin pages.

The first parameter of the hooked function is the id of the page you are on currently. In the example above, whenever that id is not edit.php the function simply returns. Otherwise it enqueues the script.

Removing and Replacing Scripts

This is by far a common scenario but every once in a while you may need to remove or replace a script. I’ve bumped into situations where a script added by a plugin (but not used by the theme) caused issues. Removing it was the best option, it made the error disappear right away.

You may also want to replace jQuery with a newer version if you’re testing something to make sure it will be compatible with newer versions.

These situations are where wp_deregister_script() and wp_dequeue_script() come in handy. Here’s how to replace WordPress’ built-in jQuery with your own:

Final Thoughts

The enqueuing method within WordPress is great because it allows you to add your scripts modularly. You can always be sure that dependencies will be loaded properly – you don’t even need to supply many of them since WordPress is full of jQuery plugins.

If you’re working with styles you can enqueue and register them in the same way, just use wp_enqueue_style(). Finally, make sure not to litter your plugin or theme with scripts. You should use as few as possible and concatenate them into one file if it makes sense.

In the next tutorial in this series, we’ll take a look at how to use AJAX to add some great functionality to your WordPress site.

Did you find this tutorial helpful? Why do you want to learn JavaScript in WordPress development? What do you want to know more about? Let us know in the comments below.

Tags:

Daniel Pataki Daniel is the CTO at Kinsta and has written for many outstanding publications like WPMU DEV and Smashing Magazine. In his spare time, you'll find him playing board games or planning the next amazing office game like the not-at-all-destructive Megaball.