Using JavaScript Correctly with WordPress

JavaScript is something that is used on 99% on websites. In the last few years it seems to have exploded and become part of the fundamental toolkit for all web developers. I see it all the time in both WordPress themes and plugins however unfortunately a lot of developers still don’t really know how to work with it correctly with WordPress.

If you’re simply including the following in your header.php you’re doing it wrong!


<!-- Scripts -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script><script type="text/javascript" src="js/bootstrap.js"></script>

WordPress gives us two functions for handling JavaScript in a way that doesn’t conflict with other plugins and themes and more importantly with the WordPress Core itself.

wp_register_script()

First up is wp_register_script() think of this as letting WordPress know about your JavaScript. When you call this function is doesn’t do anything except let WordPress know it’s there and that you might want to use it at some point.


<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

  • $handle – This is the name of the script, it should be unique as you will be using this later on in the wp_enqueue_script() function.
  • $src – This is the URL to the script. If you are using a local script you should never hardcode the URL, instead make use of the functions available such as get_template_directory_uri(). Since WordPress 3.3 you can also use protocol agnostic URLs for remotely hosted scripts. (//remotehost.com/myscript.js).
  • $deps – 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. Useful if you are registering a jQuery plugin you can specify jQuery as a dependancy.
  • $ver – String specifying the script version number, if it has one. Defaults to false (which uses the WordPress version number by default). This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the script. Set to null to disable. You can check out how to dynamically add a version number to your scripts and styles in this previous post.
  • $in_footer – Normally scripts are placed in thesection. If this parameter is true the script is placed at the bottom of the

    . This requires the theme to have the

    wp_footer()

    hook in the appropriate place. Note that you have to enqueue your script before wp_head is run, even if it will be placed in the footer.

Let’s go back to our example and see how we can register our scripts correctly.


function mojowill_scripts() {
    wp_register_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '2.2.1', false );
}

add_action( 'wp_enqueue_scripts', 'mojowill_scripts' );

I created a function and inside it called the wp_register_script() function. I am then registering a local copy of bootstrap.js. You can also see that it depends on jQuery. jQuery is one of the bundled JavaScript libraries with the WordPress core so we don’t need to register it and can simply call it as a dependancy.

wp_enqueue_script()

Next up we have wp_enqueue_script() instead of simply letting WordPress know about our script this function loads the JavaScript and outputs it in your template.


<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );?>

You’ll notice that the parameters are exactly the same as the previous function. If you have already used wp_register_script() then you can simply do the following:


<?php wp_enqueue_script( 'bootstrap' ); ?>

If we hadn’t run the register function then it would look like this:


<?php wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '2.2.1', false ); ?>

Personally I always register my scripts first. Let’s have a look at the completed code:


function mojowill_scripts() {
    wp_register_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '2.2.1', false );
    wp_enqueue_script( 'bootstrap' );
}

add_action( 'wp_enqueue_scripts', 'mojowill_scripts' );

Always remember to call your own function with the correct action hook! Use the wp_enqueue_scripts() action to call this function, or admin_enqueue_scripts() to call it on the admin side, or use login_enqueue_scripts() for login screens.

Bundled Libraries

WordPress comes with a whole heap of JavaScript libraries already included in the core so all you need to do is enqueue the script. You would use as follows:


function mojowill_builtin_scripts() {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'backbone' );
}

add_action( 'wp_enqueue_scripts', 'mojowill_builtin_scripts' );

A huge number of developers still don’t use jQuery correctly, enqueue it properly and preferably use the built in core version. If you use a different version then there is a high chance you will break plugins or themes. This is still one of the biggest issues with WordPress developers. Now there maybe times you want to use a different version of a library that is included with WordPress perhaps to take advantage of a CDN version. This is fine on your own site as long as you know what you are doing, but if you are releasing a theme or plugin publicly then for the love of God use the bundled libraries! I’m not even going to tell you here how to use a non standard version of a bundled library as personally I hate it and it’s my site so I get to write what I want!

jQuery noConflict Mode

Finally a note about jQuery. The bundled library in WordPress loads in “no-conflict” mode. This helps to stop compatibility problems with other JavaScript libraries that WordPress can load. In “no-conflict” mode the $ shortcut is not available and you instead use the longer jQuery:


// Old Way
$(document).ready(function(){
$(#myfunction)
});

// No Conflict Way
jQuery(document).ready(function(){
jQuery(#myfunction)
});

You can also use a shortcut alias, in the following examples the first piece of code will execute when the page has finished loading, however in the second example you can see how to execute the code immediately.

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

(function($) {
    // $() will work as an alias for jQuery() inside of this function
})(jQuery);

Conclusion

Do you feel all warm and fuzzy now you know how to do it properly? Probably not. Please, please, please do it the correct way though. It screws up so much other stuff when lazy developers don’t use the correct functions for JavaScript. It’s not difficult and becomes second nature very quickly!

4 thoughts on “Using Javascript with WordPress correctly

  • Thank you ;)

     Reply

  • Awesome article man! I was sourcing jQuery and company the old header way until I read this article!

     Reply

  • Can you explain, how can I pass data from Php to javascript in the correct way?

     Reply

Leave a Reply

Mojowill Avatar

Who the Hell am I?

I'm Will, a full time web developer, geek and musician. I develop using PHP and MySQL and spend most of my time working with WordPress or CakePHP. When I'm not buried in code I'm gaming, cooking or writing and recording music in my studio. I like sci-fi, pancakes and coffee and am totally prepared for the zombie apocalypse...

Stalk me on these other sites...

Why not be super creepy and check me out on all these other sites, I think they call it social media?