Best way to include jQuery and fire with script at bottom of container

I’m going to be using a jQuery slider on my homepage only (not a WP plugin, but a third party). What I’d like to do is include jQuery, the plugin’s jQuery script using a .js file, then include the script needed to fire the plugin right before the closing body tag. I’m a bit confused about how that works.

I know WordPress comes with jQuery built in, so does that mean I don’t need to include it again?

Read More

Looking for best practices on this. I understand there are conflict issues that need to be prevented, etc.

Thanks

Related posts

Leave a Reply

2 comments

  1. You typically should use the jQuery version that’s built in. There are instances where you might want to use wp_dequeue_script(‘jquery’) and then add a different version of jQuery.

    Here’s the best way to add a script dependent on jQuery:

    function theme_register_scripts(){
       wp_enqueue_script('jquery');
       wp_enqueue_script('myscript-name', get_bloginfo('stylesheet_directory') . '/js/myscript.js', array('jquery'));
    }
    add_action('wp_print_scripts', 'theme_register_scripts');
    

    The third argument of wp_enqueue_script is the script dependency which we identify as jQuery. This guarantees that jQuery will be printed before your custom script is printed.

  2. To add to that Brain said, you can use the enqueue_script function to add your js files to the footer if your theme uses wp_footer. Also when adding an action it is very useful when using javascript to use an order parameter so you can order them the way you wan’t.

    Something like:

    wp_enqueue_script('myscript-name', 
                       get_bloginfo('stylesheet_directory') . '/js/myscript.js',
                       array('jquery'), 
                       'false',  //change version #
                       'true'); //in_footer?
    
    //here we add a priority parameter to load one before the other if needed.
    add_action('wp_print_scripts', 'theme_register_scripts_other', 10);
    add_action('wp_print_scripts', 'theme_register_scripts', 20);   
    

    You can also add it to the footer using wp_footer instead of wp_print_scripts

    http://codex.wordpress.org/Function_Reference/wp_enqueue_script