• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
NameHero Blog

NameHero Blog

Web Hosting Tips & Resources From NameHero

  • Web Hosting
  • Reseller Hosting
  • Managed Cloud
  • Domains
  • Account
  • Blog Home
  • Categories

The RIGHT Way To Load jQuery From A CDN In WordPress

Bhagwad Park

Published on: November 21, 2018

Categories: WordPress 18

jQuery is a staple feature of almost all websites on the web. If a site has Javascript, it probably has jQuery. Unfortunately, this success has brought some problems with it, as explained below. While there’s no easy solution, one step towards mitigating it is to load jQuery from a CDN.

There are lots of tutorials on how to do this. Most involve simply dequeuing the script and hardcoding the new URL. However, this has plenty of problems as we’ll see.

The Problem with jQuery

Have you ever run a pagespeed test on a service like Google? Then you’ve probably seen this:

Render Blocking jQuery

These are render blocking scripts, without which your page simply won’t work. Your visitor will be left staring at a blank screen while they load in the background. As a result, it’s of critical interest that they load as fast as possible.

jQuery is the No. 1 candidate for render blocking scripts.

Why Not Just “Defer” or “Async” It?

Believe me, we’ve all tried! I’ve tried using jQuery with “async”, “defer”, and every combination of “async” and “defer” mixed with the other Javascripts known to mankind. And there’s always a problem. I still have a few untested ideas running around in my head, and I’ll let you know if I achieve success.

The crux of the problem is that many HTML elements rely on jQuery to render properly. For example, I have a plugin on my site for responsive tables that redraw themselves dynamically when the page resizes. That requires jQuery. I have a “Table of Contents” plugin that uses jQuery as well.

If you think that’s frivolous, what about lazy loading of images? Without jQuery to lend its power, this feature doesn’t work as it should. And deferring or asyncing jQuery just doesn’t work.

Bottom line: We need to live with the unhappy idea that loading jQuery cannot be put off towards the end of the page after everything has finished loading. Even if that works for you now, a time will come when you’ll need jQuery and you won’t know why your functionality is not working. It’ll be a nightmare to debug.

Loading jQuery from Google’s CDN

Once we’ve accepted our fate that we need to load jQuery before our content, our goal is to do so as quickly as possible. For this, we need a solution with the following characteristics:

  1. High probability of the user already having the resource on their system
  2. Speedy connection times (DNS lookup, server response etc)
  3. Fast download speeds

Loading jQuery from our own site only satisfies a portion of (2) on our list. The only thing our site has going for it is the fact that it doesn’t need a DNS lookup. Otherwise, the browser still has to wait for it to connect. And there almost zero chance of the visitor already having the file on their system (unless they’ve been there before).

Given all this, Google’s CDN is an excellent candidate. There’s a good chance that the user already has the jQuery file on their browser, and you can’t ask for faster connections and download speeds.

Adding Code to your WordPress

To do this, add the following code to WordPress:

add_action('init', 'use_jquery_from_google');

function use_jquery_from_google () {
	if (is_admin()) {
		return;
	}

	global $wp_scripts;
	if (isset($wp_scripts->registered['jquery']->ver)) {
		$ver = $wp_scripts->registered['jquery']->ver;
                $ver = str_replace("-wp", "", $ver);
	} else {
		$ver = '1.12.4';
	}

	wp_deregister_script('jquery');
	wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
}

If you’re not sure how to do this, check out NameHero’s knowledgebase tutorial on adding code snippets to WordPress.

What makes this code special, is that it doesn’t request any hardcoded version of jQuery. Instead, it uses the version that is already registered by WordPress. This is awesome, because it means you won’t have to remember to update your function when WordPress ships a new jQuery version.

Now sit back and enjoy your blazing fast jQuery downloads!

Bhagwad Park Profile Picture
Bhagwad Park

I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!

Reader Interactions

Comments

  1. Cyndi says

    November 21, 2018 at 4:08 pm

    I see there’s a version number in the snippet; so we would have to update that manually going forward?

    Reply
    • Bhagwad Park says

      November 26, 2018 at 1:35 pm

      That’s there just incase. In reality, there’s no reason why that branch of the “if” statement should ever be executed.

      Reply
  2. Sulabh Shrestha says

    May 29, 2019 at 2:04 pm

    This will not load jquery in WordPress 5.2 because the version that this plugin retrieves from the wordpress is 1.12.4-wp.

    There’s a “-wp” at the end which is not available in cdn jquery. So, this will return a 404 error.

    I think the only option for now is to revert to the local wordpress jquery.

    Reply
    • Bhagwad Park says

      June 3, 2019 at 5:10 pm

      You’re right! Apparently there’s a discussion on the WordPress forums about this https://core.trac.wordpress.org/ticket/47342 .

      I’ve just modified the code to remove the “-wp” part of the query. It should be working now!

      Reply
  3. omkoding says

    July 17, 2019 at 5:22 am

    Thank you, it’s working! I’ve put that code into my child theme, so it’s safe when updating the theme.

    Reply
  4. marius says

    July 21, 2019 at 8:07 pm

    great post, you save my day

    Reply
  5. marius says

    August 5, 2019 at 2:09 am

    hi, i have added the code in function.php, but i get this on debug:

    Notice: wp_deregister_script was called incorrectly. Do not deregister the jquery script in the administration area. To target the front-end theme, use the wp_enqueue_scripts hook. Please see Debugging in WordPress for more information. (This message was added in version 3.6.0.) in /var/www/……./web/wp/wp-includes/functions.php on line 4773

    how can i solve this?

    thank you

    Reply
  6. Paul Matunog says

    March 25, 2020 at 10:01 am

    Thanks for sharing this awesome code. My YSlow score has increased from 96 to 98.

    Reply
  7. Sven says

    June 7, 2020 at 4:05 am

    Quick other question, I also would like to load the jquery.smartmenus from a CDN, https://cdnjs.cloudflare.com/ajax/libs/jquery.smartmenus/1.0.1/jquery.smartmenus.min.js
    I tried to add it to your code, the smartmenus is loaded correctly but the order is out. It should first load jQuery and then smartmenus. (so I’m getting js errors)
    How do I go about managing the loading order?

    Here’s the code
    function use_jquery_from_google () {
    if (is_admin()) {
    return;
    }

    global $wp_scripts;
    if (isset($wp_scripts->registered[‘jquery’]->ver)) {
    $ver = $wp_scripts->registered[‘jquery’]->ver;
    $ver = str_replace(“-wp”, “”, $ver);
    } else {
    $ver = ‘1.12.4’;
    }
    wp_deregister_script(‘smartmenus’);
    wp_register_script(‘smartmenus’, “//cdnjs.cloudflare.com/ajax/libs/jquery.smartmenus/1.0.1/jquery.smartmenus.min.js”, false,”1.0.1″);
    wp_deregister_script(‘jquery’);
    wp_register_script(‘jquery’, “//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js”, false, $ver);

    Reply
    • Sven says

      June 7, 2020 at 4:20 am

      Meanwhile found the solution,

      I need to specify that there’s a dependency:
      wp_register_script(‘smartmenus’, “//cdnjs.cloudflare.com/ajax/libs/jquery.smartmenus/1.0.1/jquery.smartmenus.min.js”, array( ‘jquery’ ),”1.0.1″);

      Reply
  8. Nark0tiX says

    November 2, 2020 at 10:17 am

    function replaceScripts() {
    reRegister(‘jquery’, ‘//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js’, ‘1.12.4’);

    reRegister(‘jquery-selectBox’, ‘//cdnjs.cloudflare.com/ajax/libs/jquery.selectbox/1.2.0/jquery.selectBox.min.js’, ‘1.2.0’);

    reRegister(‘jquery-blockui’, ‘//cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js’, ‘2.70’);

    reRegister(‘underscore’, ‘//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.11.0/underscore.min.js’, ‘1.11.0’);

    // remove unused meuk
    wp_dequeue_script(‘contact-form-7’); // Dequeue JS Script file.
    wp_dequeue_style(‘contact-form-7’); // Dequeue CSS file.
    }

    function reRegister($name, $url, $verison) {
    wp_deregister_script($name);
    wp_register_script($name, $url, false, $version);
    wp_enqueue_script($name);
    }

    add_action(‘wp_enqueue_scripts’, ‘replaceScripts’);

    Reply
  9. Nic says

    November 25, 2020 at 2:20 am

    Thank you very much for this bit of code for jquery.
    I don’t understant why WordPress is not using a CDN Url instead, or at least an option to… That improve the loading page response on mobiles mainly.

    Reply
  10. hommealone says

    August 7, 2021 at 5:03 pm

    Great code! Thanks for this – very helpful. A couple of comments:

    Isn’t the query parameter ver self-defeating in the case of a CDN? I would think that instead of this…
    wp_register_script(‘jquery’, “//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js”, false, $ver);
    …it would be better to do this…
    wp_register_script(‘jquery’, “//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js”, array(), null, false);

    It’s much more likely that a browser would have this cached…
    https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
    …than this…
    https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js?ver=3.6.0

    That last part ( ?ver=3.6.0 ) is used as a cache buster. Since we want to use the browser’s cached version as often as possible, we don’t want a cache buster, right?

    Another question: Instead of…
    add_action(‘init’, ‘use_jquery_from_google’);
    …why wouldn’t we use this…
    add_action(‘wp_enqueue_scripts’, ‘use_jquery_from_google’);

    That works for me, and seems more appropriate. Also, since wp_enqueue_scripts runs on the front-end only, and not in the admin area, we wouldn’t need to include this part…
    if (is_admin()) {
    return;
    }

    Reply
  11. Baggo says

    September 9, 2021 at 5:14 pm

    Hello, thanks to your use of Worpress alt, my site speed has improved, thank you.

    Reply
  12. raynix says

    October 28, 2021 at 7:23 am

    This is very helpful. Thanks!

    Reply
  13. MrWP says

    July 15, 2022 at 5:43 am

    It works, thanks! I do not see changed to my PageSpeed Score, but I feel like it is faster for users to avoid a request to the self-hosted domain, thanks!

    Reply
    • Bhagwad Park says

      July 18, 2022 at 12:03 pm

      You’re welcome! Glad to see you find it useful 🙂

      Reply
  14. Ivo Kruchten says

    July 28, 2022 at 10:18 am

    Seems I Don’t get this to work.
    I get an “Uncaught TypeError: jQuery(…).on is not a function” error.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow & Subscribe

Exclusive promos, content and more!

Most Popular Posts

NameHero’s Recommended WordPress Plugin and Theme Setup (2023)

How To Increase The InnoDB Buffer Pool Size

How To Fix A Stuck All-in-One WP Migration Import

How To Add A Subdomain In Cloudflare

How To Inline And Defer CSS On WordPress Without Plugins

Top Categories

  • WordPress
  • Website Performance
  • Web Hosting
  • Resellers
  • Website Security
  • Website Development
  • VPS Hosting
  • SEO Tips
  • Announcements
  • Domain Registration
NameHero

NameHero proudly provides web hosting to over 40,000 customers with 99.9% uptime to over 750,000 websites.

  • Master Card
  • Visa
  • American Express
  • Discover
  • Paypal
Name Hero
  • Web Hosting
  • Reseller Hosting
  • Managed Cloud
  • Domains
Help & Support
  • NameHero Blog
  • Knowledgebase
  • Announcements
  • Affiliates
Company
  • About Us
  • Contact Sales
  • Reviews
  • Uptime
  • We're Hiring

Copyright © 2023 NameHero, LLC. All rights reserved.

  • Privacy Policy
  • Terms of Use
  • Acceptable Use Policy
  • Payment Policy
  • DMCA