Thursday, December 29, 2011

Effect of dependency declaration in Javascript minified code



In the following example although function foo seems longer, but in minified version it is rather smaller than the boo function.This is because compilers will rename local variables name and declaring the dependency at the beginning of the foo function allows smaller code after minification.



function boo() {
    alert(App.namespace.f1);
    alert(App.namespace.f2);
    alert(App.namespace.f3);
}
/*
minified boo
alert(App.namespace.f1);alert(App.namespace.f2);alert(App.namespace.f3)
*/




function foo() {
    var namespace = App.namespace;
    alert(namespace.f1);
    alert(namespace.f2);
    alert(namespace.f3);
}
/*
minified foo 
var a=App.namespace;alert(a.f1);alert(a.f2);alert(a.f3)
*/

No comments:

Post a Comment