1:緣由css
在寫前端代碼時, 由於要儘量的適合閱讀會加入許多註釋, 空格等, 這些在開發時是必要的, 但當你要發佈時, 就須要讓代碼更加精簡, 精簡壓縮的同時也混淆了代碼, 安全性也增強了, 能夠說是一箭雙鵰。html
2:解決方案前端
使用 htmlcompressor-1.5.3.jar(html) 和 yuicompressor-2.4.8.jar(js, css) 實現前端資源的壓縮。java
3:例子web
3.1 htmlcompressor-1.5.3.jar 壓縮 html文件瀏覽器
java -jar ./htmlcompressor-1.5.3.jar Internet.html -o Internet1.html (表示壓縮Internet.html文件中的html代碼)安全
若是, html文件中嵌入了css, 和js代碼呢?這就須要添加 --compress-js 和 --compress-css 這兩個選項來實現壓縮工具
java -jar ./htmlcompressor-1.5.3.jar Internet.html -o Internet1.html --compress-js --compress-css (表示壓縮Internet.html文件中全部代碼, 壓縮後文件更小)ui
壓縮後大小對比(小了59kb):spa
[stone web]$ ls -l Internet.html -rw-rw-r-- 1 stone stone 205671 Nov 15 10:39 Internet.html [stone web]$ ls -l Internet1.html -rw-rw-r-- 1 stone stone 145151 Nov 15 10:51 Internet1.html
內容對比圖(右邊被壓縮後的html文件更加緊湊, 卻不影響瀏覽器識別):
htmlcompressor-1.5.3.jar 也能夠壓縮js和css文件, 就是使用'--compress-js 和 --compress-css這兩個選項', 可是使用htmlcompressor-1.5.3.jar壓縮的css和js還不夠完全, 可使用專門壓縮css和js文件的工具yuicompressor-2.4.8.jar
3.2 yuicompressor-2.4.8.jar 壓縮 js 和css文件
命令: java -jar ./yuicompressor-2.4.8.jar ./js/AES.js -o test.js
壓縮後大小對比(5kb):
[stone web]$ ls -l ./js/AES.js -rw-rw-r-- 1 stone stone 9173 Nov 15 10:39 ./js/AES.js [stone web]$ ls -l ./test.js -rw-rw-r-- 1 stone stone 4057 Nov 15 10:58 ./test.js
內容對比圖(右邊被壓縮後的js文件更加緊湊, 卻不影響瀏覽器識別):
並且能夠看到, js文件的內容被壓縮到了一行上面, 而且yuicompressor還將js文件中的變量用a,b,c等來替代, 因此壓縮程度是比較高了的, 因此對人來講很不友好, 可是不影響機器識別功能。
4:使用到個人平臺
在項目中, 直接在生成image以前, 將拷貝到文件系統(rootfs)中的全部html, js, css進行壓縮以後再編譯FW便可.
參考的Makefile:
#find $(TARGET)/htdocs/web/ -type f -name *.html -exec java -jar $(TOPDIR)/progs.brand/java/htmlcompressor-1.5.3.jar {} -o {} --compress-js --compress-css \; #find $(TARGET)/htdocs/web/js ! -path "*/localization/*" -type f -name *.js ! -name MacList.js -exec java -jar $(TOPDIR)/progs.brand/java/yuicompressor-2.4.8.jar {} -o {} \; #find $(TARGET)/htdocs/web/css -type f -name *.css -exec java -jar $(TOPDIR)/progs.brand/java/yuicompressor-2.4.8.jar {} -o {} \;
通過對比, FW比沒有壓縮前端code小了1M左右