We often use a Google hosted jQuery library instead of the local jQuery library included in your WordPress installation, we often get asked how to do this and why you would want to use a Google hosted library rather than the jQuery library included in WordPress?

jQuery is a very common script that is used with most WordPress themes and plugins, as WordPress includes a copy of the jQuery library why would you want to use a copy from Google instead? The simple answer is that it will save 1 request to your server and instead load the script from the highly optimised Google network, which is probably one of the fastest available. Another reason is caching, many sites use the Google hosted jQuery Library so the chances are your visitors will have already have a cached copy of the file in their browser, meaning they won’t need to download it again when they visit your site.

Before you go ahead and change the local jQuery library for the Google version you should consider some potential conflicts. You should only change the local jQuery library if you monitor and maintain the site, this isn’t an advisable thing to do on a clients site that will be signed off and not maintained. Changes in the hosted Google library and potential conflicts within theme and plugin scripts could lead to the site becoming inaccessible.

The Google jQuery Hosted Library Function

We use this very simple function usually in the theme functions.php file but you can also make a simple plugin or use this within a Must-Use Plugin. This function simply deregisters the default jQuery script and registers and enqueues the Google Hosted jQuery library instead, you may need to change the priority.

/**
 * Enqueue Hosted Google jQuery Library
 * https://lakewood.media/wordpress-enqueue-google-hosted-jquery/
 */
function google_jquery_lakewood() { 
    if ( ! is_admin() ) {
        wp_deregister_script( 'jquery' );
        wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', false, '1.12.4' );
        wp_enqueue_script( 'jquery' );
    }
}
add_action( 'wp_enqueue_scripts', 'google_jquery_lakewood' );

You can select which library you want to enqueue from the Hosted Library Developers Documents. We use the //ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js file in most instances.