Page load performance is a big deal for retaining visitors and SEO. One of the simplest things you can do to improve performance is to use Google’s CDN-hosted jQuery.
There are some good reasons to do this and some arguments against it. I find that while you need to be careful and test your site carefully (especially after theme/plugin updates) the benefits outweigh the concerns and you should do this.
The code for this is pretty simple.
One important thing to note is that we definitely want to use WordPress’s jQuery in the admin interface. This isn’t a big deal since the main focus is to improve performance for site visitors.
The Head vs The Foot
You may notice that we’re specifying loading the Google CDN jQuery in the “foot” of the page (just before the
</body>) and wonder about that breaking plugins that load their jQuery-dependent JS in the head. Never fear – WordPress is smart enough to ignore this and load the jQuery code in the head if there are dependencies that load in the head.
Since we aren’t using the version of jQuery that comes with WordPress (which loads the jQuery Migrate plugin) there’s a chance that loading jQuery this way will break some plugins. If you’re really concerned about this, you can re-enqueue the migrate plugin in your theme after the Google CDN jQuery.
This implementation does not address the local fallback if Google’s jQuery isn’t available (for instance if you’re developing offline). Due to the way that scripts are enqueued in WordPress this is a surprisingly difficult activity to do in the standard way. We can’t just toss in the fallback snippet as bare JS.
This issue is mitigated somewhat by the fact that Google’s jQuery is cacheable for 1 year but I feel better knowing that we have a local fallback. We’ll look at a few options to handle this scenario in a future post.