Using Google’s CDN to Load jQuery, With a Local Fallback, on Your WordPress-Powered Site

By utilizing a CDN, you can save your visitors some loading time as they’ll likely already have these libraries cached.


Here’s an easy way to enqueue jQuery using Google’s Hosted Libraries with a local fallback. One of the great benefits of using a content delivery network to serve files is faster loading times for your visitors. In your theme’s functions.php, go ahead and add this:

// jQuery from Google's CDN, fallback to local if not available
add_action('wp_enqueue_scripts', 'load_external_jQuery');

// Deregister jQuery that is included with WordPress
function load_external_jQuery() {
    wp_deregister_script( 'jquery' );

// Check to make sure Google's library is available
    $link = 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
    $try_url = @fopen($link,'r');
        if( $try_url !== false ) {
            // If it's available, get it registered
            wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
    } else {
        // Register the local file if CDN fails
        wp_register_script('jquery', get_template_directory_uri().'/library/js/libs/jquery.min.js', __FILE__, false, '1.11.1', true);  
    }
    // Get it enqueued
    wp_enqueue_script('jquery');
}

You’ll likely need to change your the local path. I placed a minified version of jQuery 1.11.1 in my theme’s Javascript library folder. You can change this to use the jQuery file included with WordPress, located in the wp-includes folder. At the time of this writing, WordPress uses jQuery 1.11.1, so be sure to change that to reflect the version you need.