An easy way to trim some size off of your WordPress page loading times is to serve jQuery in your theme from the Google Libraries CDN rather than have your theme load WordPress’s internal version of jQuery which is located on your local server. I have personally used this technique a lot lately when developing WordPress themes to improve a website loading times, also by serving jQuery from Googles CDN you can easily update to the latest version of jQuery by simply changing the version number in a wordpress function.
But what about fallback if for some reason Google is unreachable and the CDN version of jQuery cannot be loaded. In the past this was a major concern but thanks a fantastic wordpress function written by Jason Witt you can now load WordPress’s local copy of jQuery if the Google CDN copy fails to load.
This code snippet will firstly run a test to see if the Google CDN version of jQuery is reachable. if it’s available it loads that version in your theme if it’s not available it will load the local copy of jQuery instead. This is a fantastic solution if your theme uses jQuery for tabs or any other features as if you soley relied on the CDN version those features would be broken for visitors if the script did not load.
I updated Jason’s original code snippet to the latest version of jQuery v1.7.2 and changed the load local jQuery function a little.
Copy The code snippet below and Paste it at the bottom of your themes functions.php file.
//------------------------- [ jQuery via Google CDN With Local Fall Back ] ------------------------// $url = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; // the URL to check against $test_url = @fopen($url,'r'); // test parameters if($test_url !== false) { // test if the URL exists function load_external_jQuery() { // load external file wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); // register the external file wp_enqueue_script('jquery'); // enqueue the external file } add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function } else { function load_local_jQuery() { wp_enqueue_script("jquery"); // enqueue the local file } add_action('wp_enqueue_scripts', 'load_local_jQuery'); // initiate the function }
As always any feedback or improvements you have please let us know with a comment.
[box type=”via ” url=”http://wp.tutsplus.com/tutorials/load-jquery-from-google-cdn-with-local-fallback-for-wordpress/”]Original Code Snippet by Jason Witt @tuts+[/box]
Leave a Reply
You must be logged in to post a comment.