YUI Compressor compresses JavaScript content including:
- Remove comments
- Remove extra spaces
- Minor optimization
- Identifier Replacement
What subtle optimizations does YUI Compressor include?
- object["property"] , if the property name is a legal JavaScript identifier (note: a legal JavaScript identifier starts with a letter, optionally followed by one or more letters, numbers, or underscores) and is not Reserved words, will be optimized to: object.property
- {"property":123}, if the property name is a legal JavaScript identifier and is not a reserved word, it will be optimized to {property:123} (Note: In object literals, if the property name is a legal JavaScript identifier and is not a reserved word and does not require quoting property names).
- 'abcd'efgh', will be optimized to "abcd'efgh".
- "abcd" + "efgh", if strings are connected, will be optimized to "abcdefgh" (Note: All under the premise of using YUI Compressor, for string connections in scripts, the efficiency and efficiency of using the connector "+" are highest maintainability).
The most effective compression optimization for JavaScript is identifier replacement.
for example:
(function(){
function add(num1, num2) {
return num1 + num2;
}
})();
After replacing the genus identifier:
(function(){
function A(C, B) {
return C+ B;
}
})();
After removing the extra spaces, we end up with:
(function(){function A(C,B){return C+B;}})();
YUI Compressor identifier replacement only replaces function names and variable names, so what cannot be replaced?
- Primitive values: string, boolean, number, null, and undefined. Generally speaking, strings occupy the most space, followed by non-numeric literals (true, false, null, underfinded).
- Global variables: window, document, XMLHttpRequest, etc. The most commonly used ones are document and window.
- Attribute name, such as: foo.bar. The space occupied is second only to strings. The "." operator cannot be replaced, and abc consumes more space.
- Keywords. Keywords that are often overused are: var, return. The best optimization method: the var and return keywords appear only once in a function.
The optimization treatment for primitive values, global variables, and attribute names is roughly the same: any literal value, global variable, or attribute name used more than 2 times (including 2 times) should be replaced by local variable storage.
However, there are some situations where identifier substitution is prohibited:
- Use the eval() function. Solution: Do not use or create a global function encapsulating eval().
- Use the with statement. Solution: The method is the same as above.
- Conditional comments for JScript. The only solution: don't use it.
Since YUI Compressor is built on the rhino interpreter , all the above optimizations are safe.
Further reading:
"Extreme JavaScript Compression With YUI Compressor"
original:
http://www.planabc.net/2009/08/02/javascript-compression_with_yui_compressor/