How to Load JavaScript in WordPress

JavaScript is one of the most popular coding languages around. It’s incredibly useful when building a website or application, and there are countless JavaScript libraries and frameworks to tap into, each readily available to speed up and streamline the development process.

With WordPress, there are a lot of moving parts that come together to make the site work. Various plugins, themes, and the core all utilize their own code, built independently of each other. If developers all do things their own way, we will inevitably run into conflicts, causing the site, at best, not to function efficiently and, at worst, break altogether.

Best Practices

To help alleviate these issues in relation to JavaScript, there are some best practices to follow when implementing it in your projects. Here’s how to best leverage JavaScript when building WordPress themes and plugins.

Load Your JavaScript the Correct Way

If you are building a static site with vanilla HTML/CSS, you can simply use JavaScript by loading it straight onto the page or typing it right inline, such as the following:

[javascript]

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js”></script>

<script>
$(document).ready(function() {
$(“#hoverTrig”).hover(function () {
$(“#subNav”).stop();
$(“#subNav”).slideToggle(400,function() {
if ($(‘#subNav’).height() < 210) {
$(“#subNav”).css({height:210})
};
});
});
});
</script>

[/javascript]

In WordPress, however, there is a different way to do it. To ensure that the same assets aren’t being loaded multiple times and that libraries and files are loaded in the correct order, WordPress gives us two functions to use. To register, or essentially make WordPress aware of the script’s existence, use wp_register_script(). To load a script onto a page, use wp_enqueue_script().

[javascript]

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

wp_register_script( $handle, $src, $deps, $ver, $in_footer );

[/javascript]

The parameters for each are the same. Let’s walk through them quickly.

  • $handle – This is the name of the script and should be unique. It’s not necessarily the filename, although I find it helpful to sync up the handle and filename for maintainability.
  • $src – The path and filename where the script is located.
  • $deps – The handles for any scripts this file is dependant on. It should be an array and is optional.
  • $ver – The version number of the script.
  • $in_footer – This is a true/false value, determining if the script should be loaded in the “footer” before the closing </body> tag of the page (true) or before the closing </head> tag (false).

Check out the WordPress Code Reference for more information on the parameters for wp_register_script and wp_enqueue_script, and to see how the functions interact together.

Using a Hook to Register and Enqueue

To ensure your scripts are ready and loaded on the front-end of your site, you’ll also want to use the wp_enqueue_scripts hook. This hook is fired when WordPress loads styles and scripts. By using it, you are making sure the scripts you want included are considered anytime WordPress loads scripts or styles.

When you use this hook, conditional logic can be incorporated to specify which pages the script should or should not be loaded on. In the following example, the yourtheme_event script is only being loaded on pages using the event.php template while the yourtheme_custom script is being loaded on every page.

[php]

function yourtheme_load_scripts() {

if ( is_page_template(‘event.php’) ) {

wp_enqueue_script( ‘yourtheme_event’, get_template_directory_uri() . ‘/js/event.js’, ‘yourtheme_custom’ );

}

wp_enqueue_script( ‘yourtheme_custom’, get_template_directory_uri() . ‘/js/custom.js’);

}

add_action( ‘wp_enqueue_scripts’, ‘yourtheme_load_scripts’ );

[/php]

Keeping Things Unique

Another important consideration when writing your own JavaScript for use in WordPress is to make your function names notably unique. If you name a function loadEvent() and another plugin also has a loadEvent() function, you’ll have some issues.

So, just like in a classroom with two students each named Sally, you’ll want to make sure there’s a way to differentiate between the two. You can either use a common prefix on functions that are unique, something like yourtheme_, or you can nest your function inside another object and avoid exposing it to the global window object.

[php]

var yourTheme = {

var loadEvent = function() {

// do something

}

}

// call the function

yourTheme.loadEvent();

[/php]

Let’s Talk About jQuery

As we wrap up, we want to make a quick note about jQuery. For a long time, many developers have struggled with implementing existing jQuery plugins in custom themes. WordPress comes with jQuery loaded out-of-the-box, so why weren’t the jQuery plugins working?

Well, WordPress loads jQuery in no conflict mode, meaning that using the widely adopted $ as an alias for jQuery doesn’t work in WordPress. digwp.com has a nice article on some options for how to work around this issue.

Get started.

Build faster, protect your brand, and grow your business with a WordPress platform built to power remarkable online experiences.