前言

JS/CSS文件压缩我们经常会用到,可以在网上找在线压缩或者本地直接使用,我这里使用的是yahoo开源组件YUI Compressor。
首先介绍一下YUI Compressor,它是一个用来压缩JS和CSS文件的工具,采用Java开发。JavaScript和CSS缩小的目标是始终保持代码的操作质量,同时减少其整体字节占用,YUI Compressor设计为100%安全的JavaScript分选程序,并且比大多数其他工具具有更高的压缩比。与JSMin相比,YUI Library 的测试节省了20%以上(HTTP压缩后为10%)。YUI Compressor还可以通过使用Isaac Schlueter的基于正则表达式的CSS minifier 的端口来压缩CSS文件。,下面为大家分享一下使用yuicompressor压缩js文件和压缩css文件。
    压缩文件可以减小文件大小,JS文件会默认去掉分号,注释,会将一些参数名改为a,b,c等,减低可读性。

YUI Compressor官网:http://yui.github.io/yuicompressor/

jar包下载:链接:https://pan.baidu.com/s/1cKM5pxgMduxBIdJRGXX9vg 提取码:q2s2

开始使用

js代码:

/**
* 验证密码和账户
*/
function validate2(username, password) {
if (username != "zhangsan") {
alert("userName is error:" + c)
}
if (password != "123456") {
alert("password is error:" + d)
}
};

进行压缩:

D:>java -jar yuicompressor-2.4.7.jar index.js -v -o index-min.js --charset UTF-8

参数说明:

index.js  需要压缩的源文件
-v -o 显示信息与指定输出文件名字
index-min.js 压缩后的文件
--charset 指定编码格式

压缩后文件:

function validate2(b,a){if(b!="zhangsan"){alert("userName is error:"+c)}if(a!="123456"){alert("password is error:"+d)}};

压缩后文件改变了参数名,去掉了分号。

不去分号:

D:>java -jar yuicompressor-2.4.7.jar index.js -v --preserve-semi -o index-min.js --charset UTF-8

压缩css:

D:>java -jar yuicompressor-2.4.7.jar index.css -v -o index1-min.css --charset UTF-8

JAVA代码

实现原理 通过java执行cmd命令,for循环遍历文件夹下js/css文件。可实现批量压缩

 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 Administrator
*
*/
public class CompressUtils {
private static final String encoding = "utf-8";
private static final String[] suffixArray = { ".js", ".css" }; public static void main(String[] args) {
String yuiPath = "D:/yuicompressor-2.4.7.jar";
String filePath = "D:/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());
} }
}
}

YUI参数使用帮助:

java -jar yuicompressor-x.y.z.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> or a file pattern.
Defaults to stdout. JavaScript Options
--nomunge Minify only, do not obfuscate
--preserve-semi Preserve all semicolons
--disable-optimizations Disable all micro optimizations GLOBAL OPTIONS -h, --help
Prints help on how to use the YUI Compressor --line-break
Some source control tools don’t like files containing lines longer than,
say 8000 characters. The linebreak option is used in that case to split
long lines after a specific column. It can also be used to make the code
more readable, easier to debug (especially with the MS Script Debugger)
Specify 0 to get a line break after each semi-colon in JavaScript, and
after each rule in CSS. --type js|css
The type of compressor (JavaScript or CSS) is chosen based on the
extension of the input file name (.js or .css) This option is required
if no input file has been specified. Otherwise, this option is only
required if the input file extension is neither ’js’ nor ’css’. --charset character-set
If a supported character set is specified, the YUI Compressor will use it
to read the input file. Otherwise, it will assume that the platform’s
default character set is being used. The output file is encoded using
the same character set. -o outfile Place output in file outfile. If not specified, the YUI Compressor will
default to the standard output, which you can redirect to a file.
Supports a filter syntax for expressing the output pattern when there are
multiple input files. ex:
java -jar yuicompressor.jar -o ’.css$:-min.css’ *.css
... will minify all .css files and save them as -min.css -v, --verbose
Display informational messages and warnings. JAVASCRIPT ONLY OPTIONS --nomunge
Minify only. Do not obfuscate local symbols. --preserve-semi
Preserve unnecessary semicolons (such as right before a ’}’) This option
is useful when compressed code has to be run through JSLint (which is the
case of YUI for example) --disable-optimizations
Disable all the built-in micro optimizations.
 

最新文章

  1. [开源].NET高性能框架Chloe.ORM-完美支持.NET Core
  2. 让Web API支持Protocol Buffers
  3. sql时间查询的问题
  4. 哈夫曼树(二)之 C++详解
  5. Android Studio快捷键每日一练(2)
  6. Ifvisible.js – 判断网页中的用户是闲置还是活动状态
  7. rman
  8. Android 通过按钮弹出系统菜单(通过Button显示菜单)转
  9. [转] mhvtl虚拟磁带库的安装与应用
  10. oracle 表查询二
  11. js保留小数点后N位的方法介绍
  12. HDOJ 2071 Max Num
  13. Struts2 技术全总结 (正在更新)
  14. android面试题之四
  15. Myeclipse 设定文件的默认打开方式
  16. Java版 人脸识别SDK demo
  17. Java面试准备之多线程
  18. mysql workbench快捷键小结
  19. ②---Java开发工具Eclipse安装配置
  20. Python自然语言处理笔记【二】文本分类之监督式分类的细节问题

热门文章

  1. monitoring_db
  2. Objective-C 小记(10)__weak
  3. caffe(13) 数据可视化(python接口)配置
  4. [SCOI2008]着色方案 递推 记忆化搜索
  5. ES6学习笔记(十四)Generator函数
  6. Ubuntu下哪个PDF阅读器更好使???
  7. 题解 CF1000E 【We Need More Bosses】
  8. Apache CXF实战之二 集成Sping与Web容器
  9. 使用glPushMatrix和glPopMatrix的原因
  10. CSS3 实现RSS图标