According to the Yahoo! Developer Network, 80% of the end-user response time is spent on the front-endlink. Since most of this time is spent downloading components, reducing the size of the components is an essential optimization.
One tool for minifying JavaScript is Google's Closure Compiler (http://closure-compiler.appspot.com/home).
Initial Minification
Suppose you have the following code (the code copies text from one textbox to another when a button is clicked):
+function(){
var input = document.querySelector("[name=input]"),
output = document.querySelector("[name=output]"),
button = document.querySelector("[name=go]");
function copy(){
output.value = input.value;
}
button.addEventListener("click",copy,false);
}();
After minification, you end with something like this (note: white space has been added for readability):
+function() {
var a = document.querySelector("[name=input]"),
b = document.querySelector("[name=output]");
document.querySelector("[name=go]").addEventListener("click", function() {
b.value = a.value
}, !1)
}();
A 24.71% reduction in size to 195 bytes.
Optimizing for minification
You may notice that one of the optimizations performed by the closure compiler is to replace variable names. This can be exploited to further reduce size.
- Variables that are used once can be in-lined
- DOM objects and functions can be made into variables (this also improves performance, see High Performance JavaScript (Build Faster Web Application Interfaces) )
- DOM global objects (e.g. window, document, etc.) can be passed as parameters
+function(document) {
var querySelector = document.querySelector;
function copy() {
querySelector.apply(document, ["[name=output]"]).value =
querySelector.apply(document, ["[name=input]"]).value;
}
querySelector.apply(document, ["[name=go]"])
.addEventListener("click", copy, false);
}(document);
The size after minification is now 181 bytes.
+function(a) {
var b = a.querySelector;
b.apply(a, ["[name=go]"]).addEventListener("click", function() {
b.apply(a, ["[name=output]"]).value = b.apply(a, ["[name=input]"]).value
}, !1)
}(document);
No comments:
Post a Comment