The correct method of adding JavaScript to a WordPress theme

A quick note to all the WordPress developments out there. If you are adding a standard JS library like jQuery or Prototype, chances are WordPress already includes a version as part of the core files. So no need to download your own copy and place in somewhere in the themes folder.

Many theme developer who rely on JS for different effects simple place the link into the template header.php. Something like this:


<script src="http://localhost/wp-content/themes/mytheme/js/jquery/jquery.js" type="text/javascript"></script>

While this does accomplish the goal of loading the JS library it also increases the chances of a second instance of the library also being loaded. Thus bloating your site.

A better option in my opinion is to add a little code to the themes functions.php file. The theme file functions.php is standard in most WordPress themes and is considered the best place to place common code that is needed by the theme. The functions.php file is automatically loaded by WordPress.


<?php
function my_functions_init() {
wp_enqueue_script('jquery');
}
add_action( 'init', 'my_functions_init' );
?>

Note we are hooking into the WordPress ‘init’ logic. We must setup the JS loading early. Some time later WordPress will load the theme. If the theme header used the theme function ‘wp_head()’ then our JS library will automatically be included. The ‘wp_head()’ function allows plugin author to insert needed JS and CSS files dynamically. Using this hook we are doing the same thing for our theme. No more hard coding the JS file link.

So how is this really “Better”?

The biggest benefit is we are preventing multiple copied of the same JS library from being loaded by WordPress or plugins. If we did hard code the JS link for jQuery and we also installed some plugin like cforms which used the jQuery library then it will load it’s own copy. By using the ‘wp_enqueue_script()’ function we are letting WordPress know we need jQuery loaded. When the plugin is loaded it will also tell WordPress is needs to load jQuery. As a result WordPress can track what JS files need to be inserted via the ‘wp_header()’ function.

For more information on the ‘wp_enqueue_script()’ function check the WordPress Codex
http://codex.wordpress.org/Function_Reference/wp_enqueue_script

About Paul Menard

Mis-placed Texas Geek now living on North Carolina. Lover of all things coding especially WordPress, Node.js, Objective-C and Swift. Love to work on interesting projects and come away with some new knowledge. Trying to keep my head on while I try to staying abreast of all the latest technologies. Lover of books and cats.