__________________________________________________________
https://wordpress.stackexchange.com/questions/12448/how-to-replace-regular-jquery-calls-with-cdn-calls-from-google/12450Notice that I'm still using WordPress' dependency management system. Also, sets HTTPS vs HTTP using
is_ssl() to avoid mixed content errors, and lets WordPress dictate version number.
//// REPLACE JQUERY WITH THE GOOGLE API version +++ get local wp version
add_action( 'init', function(){
//Only act if is admin
if ( ! is_admin()) {
//set protocol dynamically
if( is_ssl() ){
$protocol = 'https';
}else {
$protocol = 'http';
}
/** @var WP_Scripts $wp_scripts */
global $wp_scripts;
/** @var _WP_Dependency $core */
$core = $wp_scripts->registered[ 'jquery-core' ];
$core_version = $core->ver;
$core_version = str_replace("-wp", "", $core_version);
$core->src = "$protocol://ajax.googleapis.com/ajax/libs/jquery/$core_version/jquery.min.js";
///Use jQuery migrate if WP_DEBUG
if ( WP_DEBUG ) {
/** @var _WP_Dependency $migrate */
$migrate = $wp_scripts->registered[ 'jquery-migrate' ];
$migrate_version = $migrate->ver;
$migrate_version = str_replace("-wp", "", $migrate_version);
$migrate->src = "$protocol://cdn.jsdelivr.net/jquery.migrate/$migrate_version/jquery-migrate.min.js";
}else{
/** @var _WP_Dependency $jquery */
$jquery = $wp_scripts->registered[ 'jquery' ];
$jquery->deps = [ 'jquery-core' ];
}
}
}, 11 );
_____________________________________________________
/**
* Print fallback script right after jQuery is printed from queue.
*
* @param string $src
* @return string
*/
function wpse_12448_fallback_jquery( $src, $handle = null ) {
static $run_next = false;
if ( $run_next ) {
// Defaults to WP bundled jQuery, but you should use your own that
// matches the version loaded via CDN.
$local = includes_url( 'js/jquery/jquery.js' );
echo "<script>window.jQuery || document.write( '<script src=\"".$local."\"></script>' );</script>";
$run_next = false;
}
if ( $handle === 'jquery' )
$run_next = true;
return $src;
}
add_action( 'wp_head', 'wpse_12448_fallback_jquery', 2 );
if ( ! is_admin() ) {
add_filter( 'script_loader_src', 'wpse_12448_fallback_jquery', 10, 2 );
}
_____________________________________________________
Comments
Post a Comment