A Production / Development Toggle For Drupal 7 With Speedy

When we're developing websites and web applications it's useful to have a separation between a development mode and a production mode. For example, in development mode we may way to do some extra logging, disable caching, display error messages to users, and want the full source of JavaScript sent to the browser. When the site goes into production we want all the caching enabled, minified JavaScript sent to the browser, and extra logging disabled.

This idea of a development mode vs a production mode can be seen all over. If you visit the jQuery website you'll see the download has a toggle for the development or the production version. In Symfony, the frameworks whose components are making their way into Drupal 8, it has the difference between app.php (the front controller) and app_dev.php in symfony standard. A production and development version of the app. These are just two examples.

Lets take a look at how we can use the Speedy module to bring some of this concept to Drupal 7.

What Is Speedy?

Speedy is a module that supplies minified JavaScript for Drupal core. Minified JavaScript for Drupal core files is not something that works out of the box. To turn minified JavaScript on and off Speedy adds a toggle to the performance page inside Drupal. This is the feature we are looking to take advantage of.

Not sure why why minified JavaScript helps with performance? You can read more at "Why Minify JavaScript?"

Using Speedy for a Dev/Prod Toggle

Speedy stores the value of the dev/prod toggle in the Drupal variable speedy_js_production with the default value of TRUE. By default we assume the site is in production mode. To take advantage of it you just need to use variable_get('speedy_js_production', TRUE).

Let's look at an example for inserting a minified or original JavaScript file.

if (variable_get('speedy_js_production', TRUE)) {
  drupal_add_js('path/to/foo.min.js'); // The minified file
}
else {
  drupal_add_js('path/to/foo.js'); // The larger non-minified file
}

This will work even if the Speedy module is not installed because of the default value of TRUE. If the Speedy module is installed someone will be able to toggle to the non-minified script for testing and development.

Note: I realize there are more optimal ways to write this than to use an if/else setup. It's used here to make the example clear.

Drupal 8

There is an issue to "Add a Production/Development Toggle To Core" for Drupal 8. Whether this will go into Drupal 8 or not is still undecided. It will take some work. If you'd like to help out that issue is where to go.