JAVA使用YUI压缩CSS/JS
前言
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的更多相关文章
- vs合并压缩css,js插件——Bundler & Minifier
之前做了一个大转盘的抽奖活动,因为比较火,部分用户反馈看不到页面的情况,我怀疑js加载请求过慢导致,所以今天针对之前的一个页面进行调试优化. 首先想到的是对页面的js和css进行压缩优化,百度了下vs ...
- asp.net mvc项目实记-开启伪静态-Bundle压缩css,js
百度这些东西,还是会浪费了一些不必要的时间,记录记录以备后续 一.开启伪静态 如果不在web.config中配置管道开关则伪静态无效 首先在RouteConfig.cs中中注册路由 routes.Ma ...
- 用 Flask 来写个轻博客 (28) — 使用 Flask-Assets 压缩 CSS/JS 提升网页加载速度
Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 Flask-Assets 将 Flask-Assets 应用 ...
- 批量压缩 css js 文件 包含多个文件 自动识别
注意事项 css 注释压缩不会造成影响 因为是块注释 当然也可以选择去注释压缩 js 带注释压缩 要注意注意 注意 //行注释会造成 压缩后的代码在一行 导致注释后的代码都失效 ...
- 使用VS Code开发纸壳CMS自动编译主题压缩CSS,JS
Visual Studio Code (简称 VS Code / VSC) 是一款免费开源的现代化轻量级代码编辑器,支持语法高亮.智能代码补全.自定义热键.括号匹配.代码片段.代码对比 Diff.GI ...
- ASP.NET 4.0 Webform Bundles 压缩css, js,为什么放到服务器不行
参考文章: http://blog.csdn.net/dyllove98/article/details/8758149 文章说的很详细. 但是本地是可以完美展示(我的本地环境有4.0 也有4.5) ...
- yui压缩JS和CSS文件
CSS和JS文件经常需要压缩,比如我们看到的XX.min.js是经过压缩的JS. 压缩文件第一个是可以减小文件大小,第二个是对于JS文件,默认会去掉所有的注释,而且会去掉所有的分号,也会将我们的一些参 ...
- 【转载】Yui.Compressor高性能ASP.NET开发:自动压缩CSS、JS
在开发中编写的js.css发布的时候,往往需要进行压缩,以减少文件大小,减轻服务器的负担.这就得每次发版本的时候,对js.js进行压缩,然后再发布.有没有什么办法,让代码到了服务器上边,它自己进行压缩 ...
- YUI+Ant 实现JS CSS压缩
今天研究了一下YUI yahoo开源框架,感觉很猛啊. 于是乎我做了一个YUI的ant实现,网上好多关于bat的实现,我就另辟蹊径,出个关于这个的ant实现,嘿嘿独一无二的文章,如果转载的话,其注明作 ...
随机推荐
- Linux Shell脚本编程-函数
函数介绍 定义:把一段独立功能的的代码当做一个整体,并为之一个名字,命名的代码段,此即为函数: 功能:函数function是由若干条shell命令组成的语句块,实现代码重用和模块化编程. 注意: ...
- Bash 基础特性
命令别名 alias 显示当前shell中定义的所有别名 alias 别名='原始命令' unalias 别名 取消定义的别名在命令前加\使用命令本身,而不是别名(或者使用绝对路径执行命令使用命 ...
- 杀死超过5min闲置的终端
#!/bin/bash #杀死超过5min闲置的终端 while [ 1 -lt 2 ] do sleep 30 for i in `w -sh | grep ":" | awk ...
- 第四讲 Yang-Mills方程与Maxwell方程
一.变分原理 变分原理始于17世纪的速降问题,也就是连接两点的曲线在有重力的情况下,让初速度为0的一小球最快地通过? 这个问题由伯努力给出解答,他的方法非常巧妙,而最后开创了一个学科——变分学.他假设 ...
- 恐怖的奴隶主(bob)
题目 试题3:恐怖的奴隶主(bob) 源代码:bob.cpp 输入文件:bob.in 输出文件:bob.out 时间限制:1s 空间限制:512MB 题目描述 小L热衷于undercards. 在un ...
- 题解 BZOJ4919 【大根堆】
题面:传送门. 老师说今天要考一道线段树合并,然后...然后这道题我就GG了.(当然可以用线段树合并写,只是比较复杂) 有人赛时想了个贪心,然后被机房巨佬hack了,结果在hack的过程中巨佬想出了正 ...
- 【转】 HTML解析:基于XPath的C#类库HtmlAgiliytyPack
[转] HTML解析:基于XPath的C#类库HtmlAgiliytyPack 最近处于毕业设计开始阶段,前期工作需要去国外的一些专业数据库网站比对一些所需TF家族信息,为了快捷方便,想到用程序去帮助 ...
- Mysql 锁表 for update (引擎/事务)
因为之前用过oracle,知道利用select * for update 可以锁表.所以很自然就想到在mysql中能不能适应for update来锁表呢. 学习参考如下 由于InnoDB预设是Row- ...
- 解决Android Studio 2.2.3中添加.cpp .h文件在Project->Android无法显示,无法正常编译问题。
搭配使用 Android Studio 2.2 或更高版本与 Android Plugin for Gradle 版本 2.2.0 或更高版本时,您可以将 C 和 C++ 代码编译到 Gradle 与 ...
- php 扩展
如何利用PHP扩展函数,扩展出自己的函数等 php扩展函数有哪些zend_parse_parameters() spprintf() RETURN_STRINGL()