这里有一种稍微不同的方法,用CDN替换现有的排队脚本,并添加回退。还与WordPress中现有的jQuery版本相匹配。在实践中发现它非常可靠:
add_action(\'wp_enqueue_scripts\',\'jquery_cdn_with_fallback\');
function jquery_cdn_with_fallback() {
global $wp_version;
// get the jquery handle depending on WP version
$jqueryhandle = (version_compare($wp_version, \'3.6-alpha1\', \'>=\') ) ? \'jquery-core\' : \'jquery\';
// get the version of built-in Jquery in WordPress
$wpjquery = $GLOBALS[\'wp_scripts\']->registered[$jquery_handle]->ver;
$jquery = \'https://ajax.googleapis.com/ajax/libs/jquery/\'.$wpjquery.\'/jquery.min.js\';
// replace the existing jquery script URL
wp_deregister_script($jqueryhandle);
wp_register_script($jqueryhandle, $jquery, false, $jqueryversion, true);
wp_enqueue_script($jqueryhandle);
// add fallback via script_loader_tag filter
add_filter(\'script_loader_tag\',\'jquery_fallback\', 10, 2);
function jquery_fallback($scripttag, $handle) {
global $wp_version;
$jqueryhandle = (version_compare($wp_version, \'3.6-alpha1\', \'>=\') ) ? \'jquery-core\' : \'jquery\';
if ( ($handle == $jqueryhandle) && (strstr($scripttag,\'jquery.min.js\')) ) {
$jquery = urlencode(site_url().\'/wp-includes/js/jquery/jquery.js\');
// instant fallback to local WP jquery on failure
$fallback = "</script><script>if (!window.jQuery) {document.write(unescape(\'%3Cscript src=\\"".$jquery."\\"%3E%3C\\/script%3E\'));}</script>";
$scripttag = str_replace(\'</script>\',$fallback, $scripttag);
}
return $scripttag;
}
}
根据以下答案将其改编为WP:
https://stackoverflow.com/questions/1014203/best-way-to-use-googles-hosted-jquery-but-fall-back-to-my-hosted-library-on-go