Replace The Default WordPress jQuery With Updated Version
WordPress comes shipped with jQuery; as of today, I believe it's 3.7.1.
If you want to upgrade this to a different version, though, or if you'd prefer to load Google's hosted version that is likely faster loading than your self-hosted version, you can do so with this code by adding it to your functions.php file:
/**
* Replace the default jQuery with an updated version from Google's CDN.
*/
add_action( 'wp_enqueue_scripts', 'replace_default_jquery_with_google_cdn' );
function replace_default_jquery_with_google_cdn() {
$ver = '3.7.1'; // Update this to change the jQuery version.
wp_dequeue_script( 'jquery' );
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/' . $ver . '/jquery.min.js', false, $ver, true );
wp_enqueue_script( 'jquery' );
}
Simply replace the version number in this code with the version you'd like to use. This will swap the WordPress jQuery library with Google's super fast-loading version.
Or, if you'd prefer not to use Google-hosted libraries and want to self host, you can use this version:
/**
* Replace the default jQuery with updated version
*/
add_filter( 'wp_enqueue_scripts', 'replace_default_jquery_with_fallback');
function replace_default_jquery_with_fallback() {
wp_dequeue_script( 'jquery' );
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', "https://www.yourdomain.com/wp-content/themes/yourtheme/js/jquery.min.js", '', '', false ); // Replace this your jQuery link
wp_enqueue_script ( 'jquery' );
}
This will dequeue the built-in copy and load your local copy instead. Make sure to swap the example link with your self-hosted version.
September 18, 2024
hey james,
i tried this and using google's cdn really helped speed up my site's loading time!
September 24, 2024
Hey Lavenia!
That's awesome to hear! Google's CDN really can make a difference right? You might also want to try lazy loading for images if you're still looking to optimize. It made a pretty big difference on my sites!
If you have any questions I'm here to help!