WordPress Quick Tip: Load jQuery from CDN

Most people don’t realize that their websites are serving up a copy of jQuery to each and every visitor. This copy of jQuery is stored on their own servers, rather than through a CDN like Google’s Hosted Libraries.

There are legitimate reasons to host your own copy of WordPress. The most obvious is legacy support for older jQuery scripts. If your site is more than a few years old, you might not want to update your jQuery script for the sake of the functionality of your site.

If updating to a newer version of jQuery is an option for your, or you’re just looking to link to jQuery on a CDN, there are major benefits to be had. The biggeset benefit is speed. In a quick proof of concept test, I produced these speed results.

jQuery Hosted Locally

Load Time With jQuery Hosted Locally

jQuery Hosted on CDN

Load Time With jQuery Hosted Through CDN

As you can see, the speed improvements are there. I’m on what I consider a pretty good host, so you can imagine how WordPress sites (especially larger ones) on cheaper hosts could have an even greater difference between their load times.

How To Remove Locally Hosted Version of jQuery

Open your theme’s header.php file. Find the line that calls wp_head(). Immediately above that, add this line:

This line will de-register the jQuery script and prevent it from being added to your header by wp_head().

How To Add jQuery from a CDN

The only other step is to include the external copy of jQuery hosted on a CDN. If you don’t really mind where the file comes from, I suggest Google’s Hosted Libraries. Head over to the site, scroll down, and copy the latest jQuery link. Paste that into your theme’s header.php file.

Note: This may cause unintentional side effects on your site. It’s possible that you could remove multiple jQuery scripts (various jQuery plugins or extensions for example) that are required for certain parts of your theme to work properly, and it’s also possible you have plugins that are dependent on jQuery. Make sure you test this out before pushing it to your production environment – make sure it will work for you!

You’ve had fair warning, now go forth and experiment! There are page load benefits to be had on tons of WordPress sites out there with this one quick tip!

Categories Blog