Skip to content

Instantly share code, notes, and snippets.

@nfreear
Last active September 25, 2015 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfreear/1d459d4a0a21d90d21c3 to your computer and use it in GitHub Desktop.
Save nfreear/1d459d4a0a21d90d21c3 to your computer and use it in GitHub Desktop.
CDN_JS: use Javascripts via CDN in WordPress. Example: define( 'CDN_JS', '//cdn.net/path/to/a.js //path/to/b.js' );
<?php namespace Nick_Freear\WordPress;
/*
Plugin Name: CDN_JS
Plugin URI: https://gist.github.com/nfreear/1d459d4a0a21d90d21c3
Description: Quickly use Javascripts via CDN. Example: define( 'CDN_JS', '//cdn.net/path/to/a.js //path/to/b.js' ) [LACE]+
Author: Nick Freear [@IET-OU]
Author URI: https://github.com/nfreear
Version: 0.5
*/
/**
* @copyright 2015 Nick Freear.
* @license MIT
* @link http://www.jsdelivr.com/#!anchorjs
*/
class CDN_JS_Plugin {
protected $opt;
public function __construct() {
// Hook into the 'init' action
add_action( 'wp_enqueue_scripts', array( &$this, 'enqueue_scripts' ), 20 );
add_action( 'wp_footer', array( &$this, 'wp_footer' ), 99 );
if (defined( 'CDN_JS_INI' )) {
$this->opt = (object) parse_ini_string( CDN_JS_INI, $process_sections = true );
@header('X-CDN_JS_INI: '. json_encode( $this->opt ));
}
}
public function enqueue_scripts() {
if (defined( 'CDN_JS' )) {
$scripts = explode( ' ', CDN_JS );
foreach ($scripts as $idx => $js) {
wp_enqueue_script( 'cdn-js-'. $idx, $js, null, null, $in_footer = true );
}
}
$hosts = isset( $this->opt->hosts ) ? $this->opt->hosts : null;
if (isset( $this->opt->scripts )) {
foreach ($this->opt->scripts as $idx => $script) {
$js = strtr( $script, $hosts );
wp_enqueue_script( 'cdn-js-'. $idx, $js, null, null, $in_footer = true );
}
}
if (isset( $this->opt->styles )) {
foreach ($this->opt->styles as $idx => $style) {
$css = strtr( $style, $hosts );
wp_enqueue_style( 'cdn-js-'. $idx, $css );
}
}
}
public function wp_footer() {
if (!defined( 'CDN_JS_INLINE' )) return;
?>
<script id="cdn-js-inline">
<?php echo CDN_JS_INLINE ?>
</script>
<?php
}
}
$wp_cdn_js_plugin = new CDN_JS_Plugin();
/** @example
define( 'CDN_JS', 'http://nekman.github.io/keynavigator/keynavigator.js' );
define( 'CDN_JS_INI',
'
# Demo of substitution of hosts in scripts.
[hosts]
%sm = https://cdn.rawgit.com/vadikom/smartmenus/1.0.0-beta1/src
[scripts]
sm1 = %sm/jquery.smartmenus.js
nav = https://cdn.rawgit.com/tommoor/navigate-jquery-plugin/master/jquery.navigate.js
[styles]
sm2 = %sm/css/sm-core-css.css
' );
define( 'CDN_JS_INLINE',
"jQuery(function ($) {
$('#menu-menu-1 > li > a').navigate()
})" );
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment