Loading WordPress theme JavaScript the right way: Enqueue scripts

Instead of adding your theme javascript manually in the header.php/footer.php, a better way is to enqueue the files, so that they are loaded via wp_head() or wp_footer().

Here is how – add the following to your theme’s functions.php:

/*  Enqueue javascript
/* ------------------------------------ */	
function alx_scripts()  
{
	wp_enqueue_script( 'flexslider', get_template_directory_uri() . '/js/jquery.flexslider.min.js', array( 'jquery' ),'', false );
	wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ),'', true ); 
	
	if ( is_singular() && get_option( 'thread_comments' ) )	{ wp_enqueue_script( 'comment-reply' ); }
}  
add_action( 'wp_enqueue_scripts', 'alx_scripts' );  

In this example I am loading flexslider in the header, and a general theme scripts file in footer. So, if you set to true, it will load in the footer.

The comment-reply is a default WordPress javascript used for threaded comment replies. It will only load for is_singular() pages/posts and if threaded comments are enabled. In a similar fashion, you can set your other javascript files to only load for certain pages.

Both of the other examples have:

array( 'jquery' )

This means that if the file is loaded, it requires jQuery – so the default jQuery library will be loaded as well (included with WordPress by default).

Function reference: wp_enqueue_script

Written by:Alexander Agnarson

2 Responses

  1. Ash Scott says:

    Fantastic guide. Many people don’t understand what enqueueing does, but this, although it’s a short overview, sums it up perfectly. Good to see the if statement so you’re not loading the JS when not needed!

  2. Saulius says:

    Hi,
    Thanks, really useful. For about 2 hours I tried to figure it out what’s wrong with my wp_enqueue_script function. Here is the snippet:
    wp_enqueue_script(‘aside’, get_template_directory_uri() . ‘/js/aside.js’, array(‘jquery’), true); .
    So, the above code failed to load js in footer (rather than in header). After glancing at the code snippet showed in this article, I noticed that I am missing that tiny / ” / part between dependency and boolean:))
    Thanks a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *