Skip to content

Instantly share code, notes, and snippets.

@DiveWP
Last active August 29, 2015 13:57
Show Gist options
  • Save DiveWP/9497910 to your computer and use it in GitHub Desktop.
Save DiveWP/9497910 to your computer and use it in GitHub Desktop.
Enqueue the jQuery from CDN with Fallback to Local WordPress
add_action( 'wp_enqueue_scripts', 'dive_add_jquery_cdn' );
/**
* Enqueue the jQuery from CDN with fallback to local WordPress
**/
function dive_add_jquery_cdn() {
$protocol = ( isset( $_SERVER[ 'HTTPS' ] ) && 'on' == $_SERVER[ 'HTTPS' ] ) ? 'https' : 'http';
$cdn = $protocol . '://code.jquery.com/jquery-1.10.2.min.js';
$local = get_bloginfo( 'wpurl' ) . '/wp-includes/js/jquery/jquery.js';
$version = null;
wp_deregister_script( 'jquery' );
delete_transient( 'dive_setup_jquery_cdn' );
if ( 'false' == ( $repository = get_transient( 'dive_setup_jquery_cdn' ) ) ) {
$cdn = $local;
}
elseif ( false === $repository ) {
$response = wp_remote_head( $cdn );
if ( ! is_wp_error( $response ) && 200 == $response[ 'response' ][ 'code' ] ) {
set_transient( 'dive_setup_jquery_cdn', 'true', 60 * 5 );
} else {
set_transient( 'dive_setup_jquery_cdn', 'false', 60 * 5 );
$cdn = $local;
$version = '1.10.2';
}
}
wp_register_script( 'jquery', $cdn, array(), $version, false );
wp_enqueue_script( 'jquery' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment