Andy Vaughn

WordPress and jQuery

jQuery logo

WordPress natively uses jQuery. It is part of the WordPress core files, but the source can be overridden to reduce server load on your website by offloading the script source to Google’s Hosted Libraries. Here’s how to use Google as a CDN for WordPress and jQuery:

In your theme’s functions.php file, add the following code:

function queue_google_jquery() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts', 'queue_google_jquery');

And you’re done! Here’s what you did:

function queue_google_jquery() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
wp_enqueue_script( 'jquery' );
}

This code creates a new function titled “queue_google_jquery” whereby you de-register the current jQuery script variable upon loading it in wp_head() and re-assigns (wp_register_script) the variable to Google’s Hosted Library version of jQuery. It then uses the safe WordPress function “wp_enqueue_script” for adding scripts to your website. It is the safe method, because it double checks to see if it’s already loaded, there are any dependencies, etc.

Then:

add_action('wp_enqueue_scripts', 'queue_google_jquery');

This code adds the function you just created, “queue_google_jquery” as a new action to be called when the hook “wp_enqueue_scripts” loads with your WordPress website. Keep in mind, this hook is only called on the front-end, and not the Administration Dashboard. So, it reduces visitor page load and server strain, not administrative. Enjoy.

*Disclaimer this does create an external dependency on the Google servers for fetching your jQuery script. So, if the Google Hosted Libraries server goes down, so does your jQuery. I wrote an article on reliance upon Google for external services a few years ago. I’ve come to accept Google’s uptime and server reliability as top-notch. But, that is a subjective call for you to make on your own website. Good luck!

Posted by Andy Vaughn on October 3, 2012

Leave a Comment