zoukankan      html  css  js  c++  java
  • 压缩前端文件(html, css, js)

    1:原因

        在写前端代码时, 因为要尽可能的适合阅读会加入许多注释, 空格等, 这些在开发时是必要的, 但当你要发布时, 就需要让代码更加精简, 精简压缩的同时也混淆了代码, 安全性也加强了, 可以说是一举两得。

    2:解决方案

       使用 htmlcompressor-1.5.3.jar(html) 和 yuicompressor-2.4.8.jar(js, css) 实现前端资源的压缩。

    3:例子

       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文件中所有代码, 压缩后文件更小)

     压缩后大小对比(小了59kb):

    [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左右

  • 相关阅读:
    Python入门 日志打印
    Python入门 面向对象
    Python入门 更换pip源的方法
    Python入门 模块
    Python入门 函数式编程
    四月份该做的事情
    Docker入门 配置篇
    Python入门 序列章
    Python入门 值内存管理与所有的关键字
    论操作系统的IO
  • 原文地址:https://www.cnblogs.com/Flychown/p/7837913.html
Copyright © 2011-2022 走看看