SCRIPT_DEBUG in WordPress

Debugging JavaScript and CSS can be a complicated matter in WordPress. If a developer were to include any of the bundled JavaScript libraries from core (JQuery, JQuery UI, Backbone, etc), by default the minified versions of these files will always be used and concatenated.

Minification means that several steps are taken to reduce the size of the file including removing all extraneous spaces and line breaks. Concatenation takes each of these minified files and appends them all together into one document. This is a performance gain by only needing to load a single file instead of multiple smaller files.

A minified and concatenated document is very difficult to read and debug. It isn’t really feasible to set a breakpoint on a minified JavaScript file and line numbers are essentially meaningless.

Enter SCRIPT_DEBUG.

By adding the following line to your wp-config.php configuration file, WordPress will use the unminified versions of these core files:

define(‘SCRIPT_DEBUG’, true);

If you look in the wp-includes/js, wp-includes/css, wp-admin/js, and wp-admin/css directories, you will note that almost all files have two versions. For example:

autosave.js

autosave.min.js

When SCRIPT_DEBUG is set to true, the autosave.js file will be used. When the constant is set to false (default behavior), the minified autosave.min.js file will be used.

While extremely useful, this only applies to WordPress core. Themes and plugins have no obligation to use this practice. But they should!

Theme and plugin developers should absolutely include both versions of their javascript files and do a quick check against the global constant to determine which to use. Here is a simple example to include a jquery ui theme:

if(SCRIPT_DEBUG) {
wp_enqueue_style('jquery-ui-theme', get_stylesheet_directory_uri() . '/css/smoothness/jquery-ui-1.10.3.custom.css' );
} else {
wp_enqueue_style('jquery-ui-theme', get_stylesheet_directory_uri() . '/css/smoothness/jquery-ui-1.10.3.custom.min.css' );
}

This gives the benefit of both the minified and unminified versions with a minimal amount of additional code.

For more info, check out WordPress Support or reach out to us personally, on our website or on Twitter @oomphinc #debughelp.

Has debugging JavaScript and CSS been a challenge for you in the past? Was this tutorial helpful for you? Tell us in the comments!