Loading jQuery from a CDN in WordPress

This may seem like an easy task to do but is quite tricky in WordPress. Using a CDN these days is very popular, cheap and helps speed up your website taking the load off your web server. I personally love Amazon CloudFront! The tips at Google Code suggest you serve all your static content from different domains, preferably ones without cookies, so CDNs are perfect.

All the problem with WordPress is script dependancies, and this applies not only to jQuery but to all the other predefined javascript libraries (prototype, scriptaculous, thickbox, see wp_enqueue_script for more info). It’s all about the handles and plugins that use jQuery will probably use the jquery handle in their dependency lists, which will automatically make WordPress include the standard jQuery from its wp-includes directory. This means that using the code:

wp_enqueue_script("my-handle", "https://konstantin.blog/jquery.js");

You might end up including two instances of the jQuery library, one from your CDN (s.kovshenin.com) and another one from the WordPress wp-includes directory, which will end up in a total mess. Strange though, that you cannot redefine an already known handle, such as jquery like this:

wp_enqueue_script("jquery", "https://konstantin.blog/jquery.js");

The javascript library will still be loaded from the default location (wp-includes on your local web server). So the right way to do it is with a little hack in your functions.php file (in case you’re doing it within your theme) or any other plugin file (in case you’re doing it within your plugin):

add_filter('script_loader_src', 'my_script_loader_src', 10, 2);
function my_script_loader_src($src, $handle) {
	if ($handle == "jquery")
		return "https://konstantin.blog/js/jquery.1.3.2.min.js";

	return $src;
}

Then any call to wp_enqueue_script with the jquery handler will output the correct path to your CDN version of jQuery. Oh and please, try not to use generic function names like my_script_loader_src, I used that just as an example, we don’t want any function name conflicts and can’t expect other plugin/theme developers to use non-generic names ;)

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

11 comments