傳統(tǒng)的JS壓縮(刪除注釋,刪除多余空格等)提供的壓縮率有時(shí)還是不盡不意,幸虧現(xiàn)在的瀏覽器都支持壓縮傳輸(通過(guò)設(shè)置http header的Content-Encoding=gzip),可以通過(guò)服務(wù)器的配置(如apache)為你的js提供壓縮傳輸,或是appfuse中使用的GZipFilter使tomcat也提供這種能力
現(xiàn)在的問(wèn)題是這種動(dòng)態(tài)的壓縮會(huì)導(dǎo)致CPU占用率過(guò)高,現(xiàn)在我想到的解決辨法是通過(guò)提供靜態(tài)壓縮(就是將js預(yù)先通過(guò)gzip.exe壓縮好)
一.下面描述在tomcat中的應(yīng)用
1.將prototype.js通過(guò)gzip.exe壓縮保存成prototype.gzjs
2.設(shè)置header,我編寫(xiě)了一個(gè)簡(jiǎn)單的AddHeadersFilter來(lái)將所有以gzjs結(jié)尾的文件增加設(shè)置header Content-Encoding=gzip
?1????web.xml中的配置
?2?????<filter>
?3?????????<filter-name>AddHeaderFilter</filter-name>
?4?????????<filter-class>
?5?????????????badqiu.web.filter.AddHeaderFilter
?6?????????</filter-class>
?7?????????<init-param>
?8?????????????<param-name>headers</param-name>
?9?????????????<param-value>Content-Encoding=gzip</param-value>
10?????????</init-param>
11?????</filter>
12?
13?????<filter-mapping>
14?????????<filter-name>AddHeaderFilter</filter-name>
15?????????<url-pattern>*.gzjs</url-pattern>
16?????</filter-mapping>
測(cè)試prototype是否正常的代碼
?1?<html>
?2?<head>
?3?<!--?type="text/javascript"不可少,有些瀏覽器缺少這個(gè)不能運(yùn)行,具體已經(jīng)忘記了?-->
?4?<script?src="prototype.gzjs"?type="text/javascript"></script>
?5?</head>
?6?<body>
?7?????<input?id="username"?name="username"?value="badqiu"/><br?/>
?8?????<input?id="email"?value="badqiu@gmail.com"/>
?9?<script>
10?????<!--?測(cè)試prototype的方法是否正常-->
11?????alert($F('username'))
12?</script>
13?</body>
14?</html>
在Apache httpd中可以直接通過(guò)在httpd.conf增加AddEncoding x-gzip .gzjs來(lái)映射.gzjs文件的header
二.相關(guān)壓縮率數(shù)據(jù)
1. prototype.js 1.5.0_rc0原始大小56KB,未經(jīng)任何處理直接使用gzip壓縮為12KB,總壓縮率79%
2. 通過(guò)js壓縮工具壓縮過(guò)的protytype.js為20KB,使用gzip壓縮為10KB,總壓縮率為83%
3. 實(shí)際項(xiàng)目中的多個(gè)js合并成的文件 439KB,直接通過(guò)gzip壓縮為85KB,總壓縮率81%
4. 439KB經(jīng)過(guò)js壓縮為165KB,再經(jīng)過(guò)gzip壓縮為65KB,總壓縮率86%
基本上你都可以忽略js壓縮工具的壓縮率,直接使用gzip壓縮
gzip下載地址 http://www.gzip.org
tomcat的壓縮配置示例下載地址: http://m.tkk7.com/Files/badqiu/gziptest.rar