Use latest jQuery from CDN in WordPress

Advertisement:

WordPress is shipped with a current jQuery version by default. When you update your WordPress core and there’s a new version of the jQuery library that is used in the package, it will be updated, too. But you might have reasons not to update your WordPress core, want to use an outdated version of jQuery, or use the jQuery library hosted on a content distribution network (CDN). Google is hosting jQuery and other libraries publicly that you could use and include in your WordPress theme. This saves file requests to your webserver and could speed up your website a tiny bit. Also, it makes sure that only a specified version of the library is included.

In this post, I’ll show you how to use Google’s publicly available libraries in your WordPress installation. For this you’ll only need to add four rows of a function into your theme’s functions.php. If you are using a WordPress Multi-Site network or are developing on multiple themes, you could also implement that function into your shared functions file.

This is a translation of my post Das aktuelle jQuery von einem CDN in WordPress nutzen. To read it in its original German language, follow this link to the second page of this post.

Find the version you need

At the Google developer site, you’ll find the versions of the libraries they are hosting and they give you an example of how the link to each version is built. In the case of jQuery 1.12.4 the format of the link is https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js where 1.12.4 is the version number.

For using this file in your WordPress theme, you’ll simply have to add a function which removes the jQuery script that is shipped with WordPress. This function also adds the script library from the Google CDN to the queue of scripts that’s loaded within the header.

The scriplet function

That’s all about it!

Note

Note the missing http: in the script URI? It is on purpose! With leaving out the protocol, you make sure that the jQuery file is being loaded from the same protocol origin that your WordPress resides on. Otherwise, most browsers are rejecting to download and use the script due to the cross origin policy. You should not embed files from a https:// origin, if you site itself is not HTTPSed and the other way round.

Like this post? Share it!
Advertisement:

One thought on “Use latest jQuery from CDN in WordPress

Leave a Reply to AdForest Cancel Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>