How to replace regular jquery calls with CDN calls from Google?

You should be loading jQuery with wp_enqueue_script('jquery') – that way, you won’t end up with multiple instances if plugins try to load it too.

To use Google CDN, place this in your functions.php;

wp_deregister_script( 'jquery' );
wp_register_script(
    'jquery',
    'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', 
    null, // Dependencies - none
    null  // Version - use null to prevent WP adding version argument "?ver" in URL
);

Update: Personally, and I know this sounds like a cop-out, but I wouldn’t bother checking the CDN. Google is just so damn reliable, and it’s more than likely it’s already in the user’s browser cache anyway (so many sites use Google’s CDN).

However, in my duty to answer, you have one of two options;

  1. Check server side with a remote get, and if it fails, serve the local copy (expensive and not recommended)
  2. Run a script client-side that checks for jQuery, and prints the fallback if necessary

The trouble with 2) is that you need to inject this script right after jQuery, and before any other plugins that depend on it fire their scripts. The only way I know you can do this is to ‘listen’ for jQuery, then output the JavaScript on the next call.

The magic? Drop this in your functions.php;

/**
 * Print fallback script right after jQuery is printed from queue.
 *
 * @param   string $src
 * @return  string
 */
function wpse_12448_fallback_jquery( $src, $handle = null ) {
    static $run_next = false;

    if ( $run_next ) {
        // Defaults to WP bundled jQuery, but you should use your own that
        // matches the version loaded via CDN.
        $local = includes_url( 'js/jquery/jquery.js' );

        echo <<<JS
<script>window.jQuery || document.write( '<script src="https://wordpress.stackexchange.com/questions/12448/$local"></script>' );</script>

JS;
        $run_next = false;
    }

    if ( $handle === 'jquery' )
        $run_next = true;

    return $src;
}

add_action( 'wp_head', 'wpse_12448_fallback_jquery', 2 );
if ( ! is_admin() )
    add_filter( 'script_loader_src', 'wpse_12448_fallback_jquery', 10, 2 );

For those in the know, this is also hooked to wp_head right after wp_print_scripts would have fired, in case there were no more scripts to print after jquery (the function does it’s work on the next call, rather than the instance it is called with jQuery).

Leave a Comment