WordPress scripts utilities for SCRIPT_DEBUG
April 22, 2015
I've grown tired of making the same checks on SCRIPT_DEBUG over and over.
Keep debugging in mind
WordPress comes with the convenient possibility to set two separate constants while debugging: one is the well known WP_DEBUG
while the other is SCRIPT_DEBUG
.
It's good practice loading minified or uglified scripts and styles in production and, in general, anywhere SCRIPT_DEBUG
is set to true
; the usual drill is to make a check anywhere a script or style is being registered or queued:
$min = defined('SCRIPT_DEBUG`) && SCRIPT_DEBUG ? '' : '.min';
$src = plugins_url('/assets/js/script.' . $min . '.js', __FILE__);
wp_register_script('my-script', $src);
but I grew tired of doing it in each theme or plugin and tried to harness the power of WordPress to solve the problem.
Scripts
I've just pushed a WordPress plugin to GitHub and have been playing with it for one day. So far so good. The short readme has a code example I will paste
Getting proper source
WordPress allows developers to set the SCRIPT_DEBUG constant to let WordPress know that the session is a script debug one; once the Scripts class is instantiated on a root folder scripts and styles can be pulled in their normal or minified form with no additional effort.
// initialize the class on the /assets folder
$scripts = Scripts::instance(plugins_url('/assets',__FILE__);
define('SCRIPT_DEBUG', true);
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/css/style.css`
$style_src = $scripts->get_src('/css/style.css');
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/js/site.js`
$js_src = $scripts->get_src('/js/site.js');
define('SCRIPT_DEBUG', true);
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/css/style.css`
$style_src = $scripts->get_src('/css/style.css');
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/js/site.js`
$js_src = $scripts->get_src('/js/site.js');
Getting a file using just relative paths
Some files just come minified and/or are not to be scrutinized in a debug session, that's why the get method is there
define('SCRIPT_DEBUG', true);
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/vendor/vendor-style.min.css`
$style_src = $scripts->get_src('/vendor/vendor-style.min.css');
// will return `http://mysite/wp/wp-content/plugins/my-plugin/assets/vendor/vendor-script.min.js`
$js_src = $scripts->get_src('/vendor/vendor-script.min.js');