You should be loading jQuery with wp_enqueue_script('jquery') - that way, you won't end up with multiple instances if plugins try to load it too.
To use Google CDN, place this in your functions.php;
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js', array(), '1.5.1');
Update: Personally, and I know this sounds like a cop-out, but I wouldn't bother checking the CDN. Google is just so damn reliable, and it's more than likely it's already in the user's browser cache anyway (so many sites use Google's CDN).
However, in my duty to answer, you have one of two options;
- Check server side with a remote get, and if it fails, serve the local copy (expensive and not recommended)
- Run a script client-side that checks for jQuery, and prints the fallback if necessary
The trouble with 2) is that you need to inject this script right after jQuery, and before any other plugins that depend on it fire their scripts. The only way I know you can do this is to 'listen' for jQuery, then output the JavaScript on the next call.
The magic? Drop this in your functions.php;
if ( !is_admin() ) :
/**
* Hack to display fallback JavaScript *right* after jQuery loaded.
*/
function __jquery_fallback( $src, $handle = null )
{
static $run_next = false;
if ( $run_next ) {
$local = '/js/libs/jquery-1.5.1.min.js';
echo <<<JS
<script type="text/javascript">/*//<![CDATA[*/window.jQuery || document.write('<script type="text/javascript" src="$local"><\/script>');/*//]]>*/</script>
JS;
$run_next = false;
}
if ( $handle === 'jquery' )
$run_next = true;
return $src;
}
add_filter( 'script_loader_src', '__jquery_fallback', 10, 2 );
add_action( 'wp_head', '__jquery_fallback', 2 );
endif;
For those in the know, this is also hooked to wp_head right after wp_print_scripts would have fired, in case there were no more scripts to print after jquery (the function does it's work on the next call, rather than the instance it is called with jQuery).