How to include jQuery and JavaScript files correctly?

I’m doing it right now with the following code:

function uw_load_scripts() {
    // De-register the built in jQuery
    wp_deregister_script('jquery');
    // Register the CDN version
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false); 
    // Load it in your theme
    wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'uw_load_scripts' );

This works, but should I do this for everyone, like this, or for everyone but admin (so that backend uses the WordPress version?):

if (function_exists('load_my_scripts')) {  
function load_my_scripts() {  
    if (!is_admin()) {  
    wp_deregister_script( 'jquery' );  
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false); 
    wp_enqueue_script('jquery');   
    }  
}  
}  
add_action('init', 'load_my_scripts');

This version doesn’t work at all actually, I get the WordPress jQuery-version and not the Google one.

Therefore, should I deregister the jQuery that is included in WordPress at all?

Also, how do I add my own scripts (slider scripts, modernizr and my own custom.js) the correct way? I guess I should do this via functions.php as well and not in the header like I’m doing it now, but I’m unsure of how I would do that.

6

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