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实现,嘿嘿独一无二的文章,如果转载的话,其注明作 ...
随机推荐
- IBM主机上清除告警黄灯方法
机器亮黄灯告警一般是有硬件问题(单电源等可能有安全隐患的硬件配置也可能造成黄灯亮起),见到后首先进行下硬件诊断,方法如下: 诊断系统,判断是否硬件故障:1.Root用户执行diag: 2.回车后,进第 ...
- c#DataGridView复制粘贴删除功能
//可在dgv中复制.剪切.粘贴.删除数据 /// <summary> /// DataGridView复制 /// </summary> /// <param name ...
- centeros 7配置mailx使用外部smtp服务器发送邮件
发送邮件的两种方式: 1.连接现成的smtp服务器去发送(此方法比较简单,直接利用现有的smtp服务器比如qq.新浪.网易等邮箱,只需要直接配置mail.rc文件即可实现) 2.自己搭建私有的smtp ...
- python异步IO-asyncio、async和await
参考链接: asyncio:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00 ...
- caioj 1080 动态规划入门(非常规DP4:乘电梯)(dp数组更新其他量)
我一开始是这么想的 注意这道题数组下标是从大到小推,不是一般的从小到大推 f[i]表示从最高层h到第i层所花的最短时间,答案为f[1] 那么显然 f[i] = f[j] + wait(j) + (j ...
- HYSBZ1061题解
- [TJOI2017]城市(树的直径)
[TJOI2017]城市 题目描述 从加里敦大学城市规划专业毕业的小明来到了一个地区城市规划局工作.这个地区一共有ri座城市,<-1条高速公路,保证了任意两运城市之间都可以通过高速公路相互可达, ...
- Unity 模拟点击Home键和启动其他app
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehav ...
- java反射机制剖析(二)— Class Loader
上一篇博客简要的提了一下java反射机制中涉及到的一些相关知识,那么ClassLoader就是当中之中的一个.本篇博客就具体的对ClassLoader做一个相对深入的了解. 作为了解须要知道的是.事实 ...
- 參加北京bluemix云计算大会偶记
我就不写散文了.博客也要轻量化. 记录心路历程吧. 这是一次ibm的技术大会.也是传道大会,洗脑大会.会议主题看起来非常多,占领了北京国际饭店的三层,作为一个老ibm bp感受非常多. 1.北京的创业 ...