1. 程式人生 > >效能優化之YUICompressor壓縮JS、CSS

效能優化之YUICompressor壓縮JS、CSS

效能一直是專案中比較重要的一點,尤其入口網站,對頁面的響應要求是很高的,從效能角度上來講,對於Web端的優化其中重要的一點無疑是JS、CSS檔案壓縮,圖片的融合,儘量減小檔案的大小,必免佔加載時佔用過多的頻寬。yuicompressor無疑是一個比較好的壓縮工具,是yahoo的一個開源元件,下面介紹yuicompressor壓縮JS、CSS檔案,及在專案中的使用

yuicompressor介紹

1、首先需要從https://github.com/yui/yuicompressor/downloads下載yuicompressor,我用的是目前最新的2.4.7版本,下載完成後得到一個原始碼包,解壓後在build檔案中有一個yuicompressor-2.4.7.jar,一會就用這個Jar來壓縮檔案

2、yuicompressor需要有Java執行環境的支援,先通過Java -jar命令執行yuicmpressor-2.4.7.jar看下效果

longwentaodeMacBook-Pro:Downloads longwentao$ java -jar /Users/longwentao/Downloads/yuicompressor-2.4.7.jar 

Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

Global Options
  -h, --help                Displays
this information
--type <js|css> Specifies the type of the input file --charset <charset> Read the input file using <charset> --line-break <column> Insert a line break after the specified column number -v, --verbose Display informational messages and
warnings
-o <file> Place the output into <file>. Defaults to stdout. Multiple files can be processed using the following syntax: java -jar yuicompressor.jar -o '.css$:-min.css' *.css java -jar yuicompressor.jar -o '.js$:-min.js' *.js JavaScript Options --nomunge Minify only, do not obfuscate --preserve-semi Preserve all semicolons --disable-optimizations Disable all micro optimizations

—type:檔案型別(js|css)
—charset:字串編碼
—line-break:在指定的列後面插入一個line-break符號
-v,—verbose: 顯示info和warn級別的資訊
-o:指定輸出的檔案位置及檔名
—nomunge:只壓縮, 不對區域性變數進行混淆
—preserve-semi:保留所有的分號
—disable-optimizations:禁止優化

3、新建一個index.js檔案,然後使用yuicompressor壓縮,指定壓縮後的檔名為index-min.js。index.js檔案內容如下

function validate(userName,password){
    if(!userName){
        alert("userName is error:"+userName);
    }
    if(!password){
        alert("password is error:"+password);
    }
}

執行如下命令進行壓縮

java -jar /Users/longwentao/Downloads/yuicompressor-2.4.7.jar --type js --charset utf-8 -v --verbose /Users/longwentao/Downloads/index.js -o /Users/longwentao/Downloads/index-min.js

壓縮後在/Users/longwentao/Downloads/目錄下多出一個index-min.js檔案
這裡寫圖片描述

yuicompressor在專案中的應用

上面的壓縮只是單個檔案,對於批量檔案是不適合的,因此需要寫一個工具類,遞迴壓縮指定資料夾中所的有js、css檔案
在pom.xml檔案中增加對yuicompressor的引入

<!-- JS,CSS壓縮 -->
<dependency>
    <groupId>net.alchim31.maven</groupId>
    <artifactId>yuicompressor-maven-plugin</artifactId>
    <version>1.5.1</version>
</dependency>

工具類程式碼如下

package com.bug.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 通過yuicompressor壓縮JS|CSS檔案工具類
 * 
 * @author longwentao
 * @date 2016-12-17
 */
public class CompressorUtil {
    private static final String encoding = "utf-8";
    private static final String[] suffixArray = { ".js", ".css" };

    public static void main(String[] args) {
        String yuiPath = "/Users/longwentao/Downloads/yuicompressor-2.4.7.jar";
        String filePath = "/Users/longwentao/java/all_workspace/workspace_bug/bug.root/bug.web/src/main/webapp/js";

        compressFile(yuiPath, filePath);
    }

    /**
     * 壓縮指定資料夾下所有的js/css
     * 
     * @param yuiPath
     *            yuicompressor-2.4.7.jar檔案路徑
     * @param filePath
     *            要壓縮的資料夾路徑
     */
    public static void compressFile(String yuiPath, String filePath) {
        File file = new File(filePath);
        List<String> commondList = new ArrayList<String>();
        initCommondList(yuiPath, commondList, file);
        excuteCompress(commondList);
    }

    /**
     * 執行壓縮命令
     * @param commondList
     */
    private static void excuteCompress(List<String> commondList) {
        Runtime runTime = Runtime.getRuntime();
        Date startTime = new Date();
        Long count = 0L;
        for (String cmd : commondList) {
            try {
                System.out.println(cmd);
                runTime.exec(cmd);
                count++;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Date endTime = new Date();
        Long cost = endTime.getTime() - startTime.getTime();
        System.out.println("壓縮完成,耗時:" + cost + "ms,共壓縮檔案個數:" + count);
    }

    /**
     * 初始化壓縮命令
     * @param yuiPath
     * @param commondList
     * @param file
     */
    private static void initCommondList(String yuiPath,
            List<String> commondList, File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            // 如果某個資料夾是空資料夾,則跳過
            if (files == null) {
                return;
            }
            for (File f : files) {
                initCommondList(yuiPath, commondList, f);
            }
        } else {
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf("."),
                    fileName.length());

            List<String> suffixList = Arrays.asList(suffixArray);
            if (suffixList.contains(suffix)
                    && !fileName.endsWith("-min" + suffix)) {
                StringBuffer sb = new StringBuffer();
                sb.append("java -jar ");
                sb.append(yuiPath);
                sb.append(" --type ");
                sb.append(suffix.substring(suffix.indexOf(".") + 1));
                sb.append(" --charset ");
                sb.append(encoding).append(" ");
                sb.append(file.getPath()).append(" ");
                sb.append("-o").append(" ");
                sb.append(file.getPath().replace(suffix, "-min" + suffix));

                commondList.add(sb.toString());
            }

        }
    }
}

執行上面工具類中的main方法後,已經生成index-min.css,index-min.js檔案,效果如下
這裡寫圖片描述

Shell指令碼壓縮

如果是在CI環境上打包,不在本地,這時候就不能用上面提供的Java工具了,這種情況下,如果CI環境是Windows,可以提供批處理指令碼壓縮,如果是Linux,可以使用Shell指令碼批量壓縮,我的環境是Linux,Shell指令碼檔名yuicompressor.sh ,內容如下

#!/bin/sh
#clear file content
#echo > /Users/longwentao/java/shell/rcm.js
echo > /Users/longwentao/java/shell/rcm.min.js
for file in $(cat /Users/longwentao/java/shell/data.txt)
do
    cat $file >> /Users/longwentao/java/shell/rcm.js
done
java -jar /Users/longwentao/Downloads/yuicompressor-2.4.7/build/yuicompressor-2.4.7.jar --type js --charset utf-8 /Users/longwentao/java/shell/rcm.js -o /Users/longwentao/java/shell/rcm.min.js

rm /Users/longwentao/java/shell/rcm.js
echo "compression complete!!!"