Loading resources from a CDN is a great way to improve website performance. Google provides free CDN hosting for many common JavaScript library, includes the popular jQuery framework. If you’d like to load a Google CDN hosted copy of jQuery in your WordPress theme, drop the following PHP class into your functions.php
file.
/**
* Google CDN Hosted jQuery
*
* Grab Google CDN's latest jQuery with a protocol relative URL;
* fallback to local if offline. Method originall from
* HTML5 Boilerplate
*/
if ( class_exists('GoogleCDNjQuery') ):
class GoogleCDNjQuery {
// Hook into WP
function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'), 1);
}
// Modify load scripts
function enqueue_scripts() {
if ( !is_admin() ) {
wp_deregister_script('jquery');
wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, null, false);
add_filter('script_loader_src', array($this, 'local_fallback'), 10, 2);
}
wp_enqueue_script('jquery');
}
// Fallback to local file
function local_fallback($src, $handle) {
static $add_jquery_fallback = false;
if ( $add_jquery_fallback ) {
echo '<script>window.jQuery || document.write(\'<script src="' . get_template_directory_uri() . '/assets/js/vendor/jquery-1.10.2.min.js"><\/script>\')</script>' . "\n";
$add_jquery_fallback = false;
}
if ( $handle === 'jquery' ) {
$add_jquery_fallback = true;
}
return $src;
}
}
$GoogleCDNjQuery = GoogleCDNjQuery();
endif; // end class_exists
There are many advantages to loading jQuery from Google’s CDN like this, and this approach makes it very simple to do in a WordPress powered website.