To add a javascript file to your theme it is easy to use header.php in your theme folder. However, if there are plugins using the same script libraries (like jquery, scriptaculous ) it may cause errors. In this post, I will show you how to add javascript to your theme in a safe way using wp_enqueue_script.

After many plugins started embedding javascript files in WordPress using wp_head hook, WP developers created wp_enqueue_script to safely include script files. This function ensures that the library file will be loaded only once in the theme. For example, to include jquery in your themes you can easily use this call:

wp_enqueue_script('jquery');

JQuery is a common script library file that comes with WordPress so it is already defined with the jquery tag. To add a custom script you need to specify more information. To include the jquery cycle plugin you will need to use:

wp_enqueue_script('jquery'); // This will be needed by jQuery.Cycle
wp_enqueue_script('cycle', 'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js', array('jquery')); // Load jQuery.Cycle

As you can see, it is quite simpple. Let me explain this code:

'jquery'
You must specify a tag for all your scripts to avoid multiple includes.
'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js'
This is src for the script tag.
array('jquery')
In this part, you can specify dependencies using their tags in an array.

Here is another example with a custom script in the theme folder:

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

We included theme.js in the theme directory using get_template_directory_uri(). Including script files this way will ensure path will be correct even if theme directory is renamed.

It is a good practice to enqueue scripts in an init function like this:

function my_theme_scripts() {
  wp_enqueue_script( 'jquery' );
  wp_enqueue_script( 'cycle', 'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js', array( 'jquery' ) );
  wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/theme.js', 'jquery' );
}    
 
add_action('init', 'my_theme_scripts');

Just paste this code in your functions.php file and it will load the scripts in a safe and easy way.

I hope you found this tutorial useful.