Source code is for humans, live code is for machines.
I first heard Christian Heilmann state this rule at @Media Ajax 2007 as “production code is for humans, live code is for machines” but I prefer the term “source code” to “production code”. The rule was important and prescient then; now I consider it the absolute foundation of any significant web application.
Rule 1 comes into play as soon as you have a project that involves any of the following:
- More than one developer.
- You can use multiple files to hold your source code, and organize them (naming convention, file hierarchy) however you want.
- You can use lots of whitespace and comments throughout your source code.
- You can use descriptive (long) variable and function names, because the minifier will try to reduce them to one-letter variables (identifier replacement).
- Humans. Your code SHOULD be clear and comprehensible to your colleagues.
- The minifier (“compiler”). Your code SHOULD be structured to help your minifier apply its optimizations.
Personally, I am most familiar with the YUI compressor. If you choose to use it, then Nicholas Zakas’ slide deck on structuring your code for optimal optimization is required reading. In addition to helping the YUI compressor make your code even smaller, many of these tips make for tidier, more comprehensible code; and because they encourage the use of local instead of global variables, they can even make your code run faster too. Here are some of the main points:
- Any literal value used two or more times should be stored in a local variable.
- Any global variable used two or more times should be stored in a local variable.
- Any property used two or more times should be stored in a local variable.
- Try to use only one
varkeyword and one
returnstatement per function.
- Don’t use
with, or JScript conditional comments.
Where exactly you apply the concatenation and minification is up to you, and will depend on how your deployment pipeline is set up. You can do it as part of your build process, or you can do it at runtime — provided you have some form of caching enabled so that you don’t repeat the process for every request.