How to include jQuery and JavaScript files correctly?

First rule of thumb: do not deregister core-bundled scripts and replace with other versions, unless you are absolutely certain that no Theme, Plugins, or core itself will break due to the version change. Really, unless you absolutely need an alternate version of a core-bundled script, just use what is bundled with core.

Second, I strongly recommend hooking into wp_enqueue_scripts for script registering and enqueueing, rather than init. (It works at init, but from a play-nicely-with-others perspective, it’s best to use the most semantically correct hook.)

Third, to enqueue your own custom scripts, you use the same methods as above:

<?php
function wpse45437_enqueue_scripts() {
    if ( ! is_admin() ) {
        $script_path = get_template_directory_uri() . '/js/';
        // Enqueue slider script
        wp_enqueue_script( 'wpse45437_slider', $script_path . 'slider.js', array( 'jquery' ) );
        // Enqueue modernizr script
        wp_enqueue_script( 'wpse45437_modernizr', $script_path . 'modernizr.js', array( 'jquery' ) );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse45437_enqueue_scripts' );
?>

Just add whatever scripts you need to enqueue.

Leave a Comment