【发布时间】:2012-04-15 22:48:21
【问题描述】:
我注意到 minifier 在原型 javascript 中表现不佳,因为如果它们以此开头,它们不会替换任何方法或属性。例如:
// unoptimized 182 bytes
myClass.prototype.myFunction = function(){
this.myElementDom.style.backgroundColor='#000';
this.myElementDom.style.color='#FFF';
this.myElementDom.style.borderColor='#DDD';
}
// 168 bytes = 92% of unoptimized, YUI compressed
myClass.prototype.myFunction=function(){this.myElementDom.style.backgroundColor="#000";this.myElementDom.style.color="#FFF";this.myElementDom.style.borderColor="#DDD"};
// optimized 214 bytes
// set a replaceable local scope variable and reduce 2 variable
// lookups at the same time
// file-size in the development version doesn't matter, so we can even increase it
// to preserve readability
myClass.prototype.myFunction = function(){
var myElementDomStyle = this.myElementDom.style
myElementDomStyle.backgroundColor='#000';
myElementDomStyle.color='#FFF';
myElementDomStyle.borderColor='#DDD';
}
// 132 bytes = 72.53% of unoptimized, YUI compressed
myClass.prototype.myFunction=function(){var a=this.myElementDom.style;a.backgroundColor="#000";a.color="#FFF";a.borderColor="#DDD"};
万岁,节省了 19.47%...不是...在启用 gzip 的情况下发布脚本时,未优化的 YUI 压缩版本加载 130 字节(=未优化的 71.42%),显然比优化后的 YUI 节省更多具有 134 字节的压缩版本(= 73.63% 未优化)......在考虑了压缩的工作原理之后可能很明显,但是现在要走的路是什么?首先进行这种微优化和较小的压缩来证明使用 gzip 更大的文件大小是合理的......因为通过这种优化,您可以轻松地降低代码的可读性和可维护性。
【问题讨论】:
-
你可以使用谷歌闭包缩小器。另外
gzip+minify仍然比仅gzip好。 -
第二个例子不是更多的是关于减少运行时的 DOM 查找而不是寻找空间节省吗?
标签: javascript optimization compression gzip