Using JQuery From Googles CDN in a WordPress Theme

Using JQuery From Googles CDN in a WordPress Theme

I recently participated in a discussion on the WordPress forums about how to call jQuery from Googles CDN rather than using the version that comes with WordPress.

The reason to use the Google CDN is that it is typically faster than your webhosting and may make the jquery functions in themes and plugins run more quickly.

The information that I’m sharing below is how you can do this – from within your theme.  However, the code can also be used within plugins you write because with WordPress, you can add functions that you would normally run in a plugin from functions.php.

Add the code below, in your themes functions.php file to load JQuery from Google.

function add_google_jquery() {
if ( !is_admin() ) {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js', false);
wp_enqueue_script('jquery');
}
}
add_action('wp_print_scripts ', 'add_google_jquery');

Let’s work through this:

wp_deregister_script('jquery');

Will remove any other definition for jQuery in your theme (see wp_deregister_script)

The next two lines define how to load jQuery from Google:

wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js', false);
wp_enqueue_script('jquery');

The wp_register_script function will define a script to a ‘handle’ or a ‘name’.  In our case, the script at Google will be known by the handle, jquery.

The wp_enqueue_script is pretty funky.  Thanks to the WordPress code framework, when the function is called it will add the script appropriately.

The last part, after the function:
add_action(‘wp_print_scripts’,'add_google_jquery’);

Basically tells WordPress to run your function add_google_jquery just before WordPress prints registered JavaScript scripts into the page header (wp_print_scripts).

The add_action on ‘wp_print_scripts‘ will run all the commands in the function you define and it’s worthwhile spending some time looking at the Action Reference for WordPress.

To test if your function is working, load your site without the function active. Check your page source and see what / where jquery is loaded – in most standard WP Themes, it’s called from the wp-includes folder.

Activate your function, load your site with the function activated and check the page source again. If the function is working correctly, you’ll see jquery being loaded from the Google CDN.

Powered by WishList Member - Membership Site Software