性能优化之YUICompressor压缩JS、CSS

来源:互联网 发布:小票打印机软件 编辑:程序博客网 时间:2024/05/14 19:55

性能一直是项目中比较重要的一点,尤其门户网站,对页面的响应要求是很高的,从性能角度上来讲,对于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' *.jsJavaScript 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.jsecho > /Users/longwentao/java/shell/rcm.min.jsfor file in $(cat /Users/longwentao/java/shell/data.txt)do    cat $file >> /Users/longwentao/java/shell/rcm.jsdonejava -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.jsrm /Users/longwentao/java/shell/rcm.jsecho "compression complete!!!"
0 0
原创粉丝点击