Created
May 8, 2015 14:59
-
-
Save spacedmonkey/0ef1258e70341b81e445 to your computer and use it in GitHub Desktop.
WordPress load jquery from CDN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class jQuery_CDN { | |
/** | |
* @var int | |
*/ | |
private $jquery_version = 0; | |
/** | |
* @var int | |
*/ | |
private $jquery_url = null; | |
private $already_run = false; | |
/** | |
* | |
*/ | |
function __construct() { | |
if ( is_admin() ) { | |
return; | |
} | |
add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 100 ); | |
add_filter( 'script_loader_tag', array( $this, 'filter_script_loader_src' ), 100, 2 ); | |
} | |
function action_wp_enqueue_scripts() { | |
global $wp_scripts; | |
$this->setJqueryVersion( $wp_scripts->registered['jquery-core']->ver ); | |
$this->setJqueryUrl( site_url( $wp_scripts->registered['jquery-core']->src ) ); | |
$jquery_version = $this->getJqueryVersion(); | |
wp_deregister_script( 'jquery' ); | |
wp_register_script( | |
'jquery', | |
'//ajax.googleapis.com/ajax/libs/jquery/' . $jquery_version . '/jquery.min.js', | |
array(), | |
$jquery_version, | |
true | |
); | |
} | |
/** | |
* Output the local fallback immediately after jQuery's <script> | |
* | |
* @link http://wordpress.stackexchange.com/a/12450 | |
*/ | |
function filter_script_loader_src( $src, $handle = null ) { | |
if ( $handle !== 'jquery' ) { | |
return $src; | |
} | |
if ( $this->isAlreadyRun() ) { | |
return $src; | |
} | |
$src .= '<script>window.jQuery || document.write(\'<script src="' . $this->getJqueryUrl() . '"><\/script>\')</script>' . "\n"; | |
$this->setAlreadyRun( true ); | |
return $src; | |
} | |
/** | |
* @return int | |
*/ | |
public function getJqueryUrl() { | |
return $this->jquery_url; | |
} | |
/** | |
* @param int $jquery_url | |
*/ | |
public function setJqueryUrl( $jquery_url ) { | |
$this->jquery_url = $jquery_url; | |
} | |
/** | |
* @return int | |
*/ | |
public function getJqueryVersion() { | |
return $this->jquery_version; | |
} | |
/** | |
* @param int $jquery_version | |
*/ | |
public function setJqueryVersion( $jquery_version ) { | |
$this->jquery_version = $jquery_version; | |
} | |
/** | |
* @return boolean | |
*/ | |
public function isAlreadyRun() { | |
return $this->already_run; | |
} | |
/** | |
* @param boolean $already_run | |
*/ | |
public function setAlreadyRun( $already_run ) { | |
$this->already_run = $already_run; | |
} | |
} | |
$test = new jQuery_CDN(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment