As a follow up to my previous post on using a CDN jQuery in your website.
If you use WordPress (with Genesis Framework) and want to take advantage of a CDN (Content Delivery Network) hosted jQuery library to your theme, edit your functions.php
file to include these codes:
if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.1.min.js', false, '1.11.1'); wp_enqueue_script('jquery'); }
The codes above will include jQuery CDN on your site, but not the fallback method mentioned in this post. To implement a similar fallback solution in WordPress/Genesis, just add these lines into your functions.php
in your child theme directory:
// De-register default jQuery from WordPress if (!is_admin()) { wp_deregister_script('jquery'); } // Replace DOCTYPE to HTML5 and include CDN-hosted jQuery and fallback method remove_action('genesis_doctype', 'genesis_do_doctype'); add_action('genesis_doctype', 'child_do_doctype'); function child_do_doctype() { ?> <!DOCTYPE html> <html <?php language_attributes(); ?>> <head profile="http://gmpg.org/xfn/11"> <meta charset="<?php bloginfo('charset'); ?>" /> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script> <script>!window.jQuery && document.write('<script src="/js/jquery-1.11.1.min.js"></script>')</script> <?php } ...
This will not only add the jQuery CDN and a fallback method, but also replaces the DOCTYPE heading to HTML5 in your Genesis Theme.
One caution before you do this. Make sure all plugins, especially the old ones, are tested for compatibility with the jQuery version you want to use.
All the above examples use jQuery library hosted on Microsoft CDN. If you want to use other CDN hosts, just change the URL address in the src
tag. For example, to use jQuery from Google CDN, you have to use this address instead (everything else should be the same):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Update
With the newer version of WordPress and Genesis, the better and easier way to do this is just to de-register the default jQuery in function.php
using the following codes:
// De-register default jQuery from WordPress if ( !is_admin() ) { add_action( 'wp_print_scripts', 'de_script', 100 ); function de_script() { wp_dequeue_script( 'jquery' ); wp_deregister_script( 'jquery' ); wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', false, 1.11.1, true); wp_enqueue_script('jquery'); } }
The last parameter true will add the jquery in the footer instead of header, which is a better way for performance sake.
Further Reading
Function Reference/wp register script
Function Reference / wp dequeue script
Leave a Reply