Last Updated: February 25, 2016
·
1.234K
· japh

Load JavaScript Correctly With wp_enqueue_script();

A basic usage example of the correct way to load JavaScript for a WordPress theme:

function wptuts_scripts_basic()
{
    // Register the script like this for a plugin:
    wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
    // or
    // Register the script like this for a theme:
    wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

    // For either a plugin or a theme, you can then enqueue the script:
    wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );

This example was taken from my article on Wptuts+ that goes into more detail on the subject of including JavaScript and Cascading Stylesheets in WordPress: http://wp.tutsplus.com/articles/how-to-include-javascript-and-css-in-your-wordpress-themes-and-plugins/