前言

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.
 

JAVA使用YUI压缩CSS/JS的更多相关文章

  1. vs合并压缩css,js插件——Bundler & Minifier

    之前做了一个大转盘的抽奖活动,因为比较火,部分用户反馈看不到页面的情况,我怀疑js加载请求过慢导致,所以今天针对之前的一个页面进行调试优化. 首先想到的是对页面的js和css进行压缩优化,百度了下vs ...

  2. asp.net mvc项目实记-开启伪静态-Bundle压缩css,js

    百度这些东西,还是会浪费了一些不必要的时间,记录记录以备后续 一.开启伪静态 如果不在web.config中配置管道开关则伪静态无效 首先在RouteConfig.cs中中注册路由 routes.Ma ...

  3. 用 Flask 来写个轻博客 (28) — 使用 Flask-Assets 压缩 CSS/JS 提升网页加载速度

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 Flask-Assets 将 Flask-Assets 应用 ...

  4. 批量压缩 css js 文件 包含多个文件 自动识别

    注意事项  css 注释压缩不会造成影响      因为是块注释     当然也可以选择去注释压缩 js 带注释压缩  要注意注意 注意  //行注释会造成 压缩后的代码在一行 导致注释后的代码都失效 ...

  5. 使用VS Code开发纸壳CMS自动编译主题压缩CSS,JS

    Visual Studio Code (简称 VS Code / VSC) 是一款免费开源的现代化轻量级代码编辑器,支持语法高亮.智能代码补全.自定义热键.括号匹配.代码片段.代码对比 Diff.GI ...

  6. ASP.NET 4.0 Webform Bundles 压缩css, js,为什么放到服务器不行

    参考文章: http://blog.csdn.net/dyllove98/article/details/8758149 文章说的很详细. 但是本地是可以完美展示(我的本地环境有4.0 也有4.5) ...

  7. yui压缩JS和CSS文件

    CSS和JS文件经常需要压缩,比如我们看到的XX.min.js是经过压缩的JS. 压缩文件第一个是可以减小文件大小,第二个是对于JS文件,默认会去掉所有的注释,而且会去掉所有的分号,也会将我们的一些参 ...

  8. 【转载】Yui.Compressor高性能ASP.NET开发:自动压缩CSS、JS

    在开发中编写的js.css发布的时候,往往需要进行压缩,以减少文件大小,减轻服务器的负担.这就得每次发版本的时候,对js.js进行压缩,然后再发布.有没有什么办法,让代码到了服务器上边,它自己进行压缩 ...

  9. YUI+Ant 实现JS CSS压缩

    今天研究了一下YUI yahoo开源框架,感觉很猛啊. 于是乎我做了一个YUI的ant实现,网上好多关于bat的实现,我就另辟蹊径,出个关于这个的ant实现,嘿嘿独一无二的文章,如果转载的话,其注明作 ...

随机推荐

  1. 51Nod 不重叠的线段(贪心)

    X轴上有N条线段,每条线段有1个起点S和终点E.最多能够选出多少条互不重叠的线段.(注:起点或终点重叠,不算重叠). 例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重 ...

  2. 联想 M415 I3-6100 CPU安装系统方法

    问题: 直接用PE GHOST系统后,USB无法使用,导致鼠标.U盘也无法使用 即 无法安装驱动.软件等 方法: 1.按网上方式,安装集成USB3.0的PE系统 2. 直接用PS2鼠标安装

  3. 判断页面是否被嵌入iframe里面

    最近在做一个项目,是一个小型的后台管理系统,这个系统可以单独打开,也可以嵌入公司大型的后台管理项目里面 这样就存在一个问题,在被嵌入大的后台管理系统后,不用显示该页面顶部导航栏和左侧的菜单栏 所以我们 ...

  4. 常用模块(hashlib、suprocess、configparser)

    hashlib模块 hash是一种接受不了内容的算法,(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算 ...

  5. vue深究第一弹:computed与watch的异同

    最近在开发vue的过程中,不断用到了计算属性(computed)和观察者(watch),从逻辑上感觉它们很相似,但是尝试混用它们的时候,又出现了一些问题,那么它们到底有什么异同呢? 1. comput ...

  6. ECNUOJ 2615 会议安排

    会议安排 Time Limit:1000MS Memory Limit:65536KB Total Submit:451 Accepted:102 Description 科研人员与相关领域的国内外同 ...

  7. PatentTips - Posting interrupts to virtual processors

    BACKGROUND Generally, the concept of virtualization in information processing systems allows multipl ...

  8. CODEVS——T 2833 奇怪的梦境

    http://codevs.cn/problem/2833/  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解  查看运行结果     题目描述 Descr ...

  9. 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】

    [063-Unique Paths II(唯一路径问题II)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Follow up for "Unique Pa ...

  10. leetcode第一刷_Text Justification

    这个题的接受率好低,搞得我一直不敢做.后来认真的看了一下题目,不是非常难嘛.字符串的题目ac率就是低,除了难,还由于它的測试用例太多. 思路不难,主要是由于特殊情况太多.纯模拟,我把全部的情况罗列一下 ...