性能优化之YUICompressor压缩JS、CSS

性能优化之YUICompressor压缩JS、CSS性能一直是项目中比较重要的一点,尤其门户网站,对页面的响应要求是很高的,从性能角度上来讲,对于Web端的优化其中重要的一点无疑是JS、CSS文件压缩,图片的融合,尽量减小文件的大小,必免占加载时占用过多的带宽。yuicompressor无疑是一个比较好的压缩工具,是yahoo的一个开源组件,下面介绍yuicompressor压缩JS、CSS文件,及在项目中的使用yuicmpressor的使用1、首先

大家好,又见面了,我是你们的朋友全栈君。

性能一直是项目中比较重要的一点,尤其门户网站,对页面的响应要求是很高的,从性能角度上来讲,对于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' *.js
JavaScript 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.js
echo > /Users/longwentao/java/shell/rcm.min.js
for file in $(cat /Users/longwentao/java/shell/data.txt)
do
    cat $file >> /Users/longwentao/java/shell/rcm.js
done
java -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.js

rm /Users/longwentao/java/shell/rcm.js
echo "compression complete!!!"
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/161225.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 字符串反转的实现方法总结「建议收藏」

    文章目录方法1:对称交换法方法2:函数递归法方法3:列表反转法方法4:循环反向迭代法方法5:倒序切片法方法6:遍历索引法方法7:反向遍历索引法方法8:列表弹出法方法9:反向循环迭代法方法10:累积相加法方法11:匿名函数法方法12:列表倒序法方法13:双向队列排序法方法14:双向队列反转法方法1:对称交换法str=’abcdef’deff(s):s=list(s)…

    2022年4月16日
    41
  • SpringBoot整合RabbitMQ之 典型应用场景实战一「建议收藏」

    SpringBoot整合RabbitMQ之 典型应用场景实战一「建议收藏」实战前言RabbitMQ作为目前应用相当广泛的消息中间件,在企业级应用、微服务应用中充当着重要的角色。特别是在一些典型的应用场景以及业务模块中具有重要的作用,比如业务服务模块解耦、异步通信、高并发限流、超时业务、数据延迟处理等。其中课程的学习链接地址:https://edu.csdn.net/course/detail/9314RabbitMQ官网拜读首先,让我们先拜读Ra…

    2022年5月14日
    33
  • 计算机一级ip地址分类,IP地址分类和子网划分[通俗易懂]

    计算机一级ip地址分类,IP地址分类和子网划分[通俗易懂]一、IP地址1、IP地址概述§在一个IP网络中每一个设备的唯一标识符,有32位二进制数组成,这些位通常被分割成四组,每组包含一个字节(8位)。然后转换成十进制表示,这叫点分十进制表示法。§每一个主机(计算机,网络设备,外围设备)必须有一个唯一的地址。§IP地址由网络ID和主机ID组成,网络ID:标识某个网段,在同一个网段的计算机,它们的网络ID是一样的,不同网段的计算机,它们的网络ID…

    2022年6月5日
    37
  • Mac下利用Anaconda安装Opencv「建议收藏」

    Mac下利用Anaconda安装Opencv「建议收藏」打开Anaconda,选择Environments,打开需要安装环境的终端输入以下代码sudopipinstallopencv-python-ihttps://pypi.tuna.tsinghua.edu.cn/simple记住命令前加sudo,否则会报错填写密码后即可安装验证安装是否成功方法1importcv2没错报错就表明安装成功方法2condalist找到opencv库则表明安装成功!!Reference添加链接描述添加链接描述…

    2022年8月30日
    3
  • js 正则替换换行符

    js 正则替换换行符vardiv=document.getElementById(‘div’);vars=div.innerHTML.replace(/(\n|\r|(\r\n)|(\u0085)|(\u2028)|(\u2029))/g,””);//g的意思是:执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。//取消了空格之后在做其他的替换才可以,否则不能替换

    2022年5月24日
    140
  • 研究院‘产品会议’操作实践

    研究院‘产品会议’操作实践

    2022年3月11日
    51

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号