Load jQuery from CDN, fallback to local (for Wordpress)


/ Published in: PHP
Save to your folder(s)

Add the following to your Wordpress theme's functions.php file. The jQuery paths/URLs might need to be changed to suite your circumstances.


Copy this code and paste it in your HTML
  1. /**
  2.  * Load jQuery from Google CDN, fallback to local
  3.  */
  4. // http://wp.tutsplus.com/tutorials/load-jquery-from-google-cdn-with-local-fallback-for-wordpress/
  5. if( !is_admin()){ // Don't do this for admin area, since Google's jQuery isn't in noConflict mode and will interfere with WP's admin area.
  6. $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'; // the URL to check against
  7. $test_url = @fopen($url,'r'); // test parameters
  8. if($test_url !== false) { // test if the URL exists
  9. function load_external_jQuery() { // load external file
  10. wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery
  11. wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'); // register the external file
  12. wp_enqueue_script('jquery'); // enqueue the external file
  13. }
  14. add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function
  15. } else {
  16. function load_local_jQuery() {
  17. wp_deregister_script('jquery'); // deregisters the default WordPress jQuery
  18. wp_register_script('jquery', get_bloginfo('template_url').'/js/jquery-1.6.2.min.js', __FILE__, false, '1.6.2', true); // register the local file
  19. wp_enqueue_script('jquery'); // enqueue the local file
  20. }
  21. add_action('wp_enqueue_scripts', 'load_local_jQuery'); // initiate the function
  22. }
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.