Table of Contents
from: 使用wro4j和maven在编译期间压缩js和css文件
Home Web Front-end HTML Tutorial 前端js和css的压缩合并之wro4j_html/css_WEB-ITnose

前端js和css的压缩合并之wro4j_html/css_WEB-ITnose

Jun 21, 2016 am 08:52 AM

me:注:

找了一圈,在java社区和node社区,就没有找到中意的解决方案,总是带有各种各样的毛病。

看来ror社区还是拥有最强悍的设计和构架能力的,也许得益于ruby的精神。

最牛牛的人有时候只要一两个就够了。

下面的文还是不错的,可惜wro4j的愚笨复杂设计啊。

from: 使用wro4j和maven在编译期间压缩js和css文件

最近在对一个web系统做性能优化. 

而对用到的静态资源文件的压缩整合则是前端性能优化中很重要的一环. 

好处不仅在于能够减小请求的文件体积,而且能够减少浏览器的http请求数. 

因为是基于java的web系统,并且使用的是nginx+tomcat做为服务器. 

最后考虑用wro4j和maven plugin在编译期间压缩静态资源. 

优化前: 

基本上所有的jsp都引用了这一大坨静态文件: 

<link rel="stylesheet" type="text/css" href="${ctxPath}/css/skin.css"/>  <link rel="stylesheet" type="text/css" href="${ctxPath}/css/jquery-ui-1.8.23.custom.css"/>  <link rel="stylesheet" type="text/css" href="${ctxPath}/css/validationEngine.jquery.css"/>    <script type="text/javascript">var GV = {ctxPath: '${ctxPath}',imgPath: '${ctxPath}/css'};</script>  <script type="text/javascript" src="${ctxPath}/js/jquery-1.7.2.min.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery-ui-1.8.23.custom.min.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.validationEngine.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.validationEngine-zh_CN.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.fixedtableheader.min.js"></script>  <script type="text/javascript" src="${ctxPath}/js/roll.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.pagination.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.rooFixed.js"></script>  <script type="text/javascript" src="${ctxPath}/js/jquery.ui.datepicker-zh-CN.js"></script>  <script type="text/javascript" src="${ctxPath}/js/json2.js"></script>  <script type="text/javascript" src="${ctxPath}/js/common.js"></script>  
Copy after login

引用的文件很多,并且文件体积没有压缩,导致页面请求的时间非常长.

另外还有一个问题,就是为了能够充分利用浏览器的缓存,静态资源的文件名称最好能够做到版本化控制.

这样前端web服务器就可以放心大胆的开启缓存功能而不用担心缓存过期问题,因为如果一旦静态资源文件有修改的话,

会重新生成一个文件名称.

下面我根据自己项目的经验,来介绍下如何较好的解决这两个问题.

分两步进行.

第一步:引入wro4j,在编译时期将上述分散的多个文件整合成少数几个文件,并且将文件最小化.

第二步:在生成的静态资源文件的文件名称上加入时间信息

这是两步优化之后的引用情况:

${platform:cssFile("/wro/basic") }  <script type="text/javascript">var GV = {ctxPath: '${ctxPath}',imgPath: '${ctxPath}/css'};</script>  ${platform:jsFile("/wro/basic") }  ${platform:jsFile("/wro/custom") }  
Copy after login

只引用了1个css文件,2个js文件.http请求从10几个减少到3个,并且整体文件体积缩小了近一半.

下面介绍优化流程.

第一步:合并并且最小化文件.

1.添加wro4j的maven依赖

<wro4j.version>1.6.2</wro4j.version>       ...     <dependency>    <groupId>ro.isdc.wro4j</groupId>    <artifactId>wro4j-core</artifactId>    <version>${wro4j.version}</version>    <exclusions>     <exclusion>       <!-- 因为项目中的其他jar包已经引入了不同版本的slf4j,所以这里避免jar重叠所以不引入 -->      <groupId>org.slf4j</groupId>      <artifactId>slf4j-api</artifactId>     </exclusion>    </exclusions>   </dependency>  
Copy after login

2.添加wro4j maven plugin

   <plugin>      <groupId>ro.isdc.wro4j</groupId>      <artifactId>wro4j-maven-plugin</artifactId>      <version>${wro4j.version}</version>      <executions>       <execution>        <phase>compile</phase>        <goals>         <goal>run</goal>        </goals>       </execution>      </executions>      <configuration>       <targetGroups>basic,custom</targetGroups>        <!-- 这个配置是告诉wro4j在打包静态资源的时候是否需要最小化文件,开发的时候可以设成false,方便调试 -->       <minimize>true</minimize>       <destinationFolder>${basedir}/src/main/webapp/wro/</destinationFolder>       <contextFolder>${basedir}/src/main/webapp/</contextFolder>    <!-- 这个配置是第二步优化需要用到的,暂时忽略 -->       <wroManagerFactory>com.rootrip.platform.common.web.wro.CustomWroManagerFactory</wroManagerFactory>      </configuration>           </plugin>  
Copy after login

如果开发环境是eclipse的话,可以下载m2e-wro4j这个插件.

下载地址:http://download.jboss.org/jbosstools/updates/m2e-wro4j/

这个插件的主要功能是能够帮助我们在开发环境下修改对应的静态文件,或者pom.xml文件的时候能够自动生成打包好的js和css文件.

对开发来说就会方便很多.只要修改源文件就能看见修改后的结果.

3.在WEB-INF目录下添加wro.xml文件,这个文件的作用就是告诉wro4j需要以怎样的策略打包jss和css文件.

<?xml version="1.0" encoding="UTF-8"?>  <groups xmlns="http://www.isdc.ro/wro" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.isdc.ro/wro wro.xsd">     <group name="basic">    <css>/css/basic.css</css>    <css>/css/skin.css</css>    <css>/css/jquery-ui-1.8.23.custom.css</css>    <css>/css/validationEngine.jquery.css</css>        <js>/js/jquery-1.7.2.min.js</js>    <js>/js/jquery-ui-1.8.23.custom.min.js</js>    <js>/js/jquery.validationEngine.js</js>    <js>/js/jquery.fixedtableheader.min.js</js>    <js>/js/roll.js</js>    <js>/js/jquery.pagination.js</js>    <js>/js/jquery.rooFixed.js</js>    <js>/js/jquery.ui.datepicker-zh-CN.js</js>    <js>/js/json2.js</js>   </group>      <group name="custom">    <js>/js/jquery.validationEngine-zh_CN.js</js>    <js>/js/common.js</js>   </group>    </groups>  
Copy after login

官方文档:http://code.google.com/p/wro4j/wiki/WroFileFormat

其实这个配置文件很好理解,如果不愿看官方文档的朋友我在这简单介绍下.

上面这样配置的目的就是告诉wro4j要将

/css/basic.css

/css/skin.css

/css/jquery-ui-1.8.23.custom.css

/css/validationEngine.jquery.css

这四个文件整合到一起,生成一个叫basic.css的文件到指定目录(wro4j-maven-plugin里配置的),将

/js/jquery-1.7.2.min.js

/js/jquery-ui-1.8.23.custom.min.js

/js/jquery.validationEngine.js

/js/jquery.fixedtableheader.min.js

/js/roll.js

/js/jquery.pagination.js

/js/jquery.rooFixed.js

/js/jquery.ui.datepicker-zh-CN.js

/js/json2.js

这几个文件整合到一起,生成一个叫basic.js的文件到指定目录.

最后将

/js/jquery.validationEngine-zh_CN.js

/js/common.js

这两个文件整合到一起,,生成一个叫custom.js的文件到指定目录.

第一步搞定,这时候如果你的开发环境是eclipse并且安装了插件的话,应该就能在你工程的%your webapp%/wor/目录下看见生成好的

basic.css,basic.js和custom.js这三个文件了.

然后你再将你的静态资源引用路径改成

<link rel="stylesheet" type="text/css" href="${ctxPath}/wro/basic.css"/>  <script type="text/javascript" src="${ctxPath}/wro/basic.js"></script>  <script type="text/javascript" src="${ctxPath}/wro/custom.js"></script>  
Copy after login

就ok了.每次修改被引用到的css或js文件的时候,这些文件都将重新生成.

如果开发环境是eclipse但是没有安装m2e-wro4j插件的话,pom.xml可能需要额外配置.

请参考: https://community.jboss.org/en/tools/blog/2012/01/17/css-and-js-minification-using-eclipse-maven-and-wro4j

第二步:给生成的文件名称中加入时间信息并通过el自定义函数引用脚本文件.

1. 创建DailyNamingStrategy类

public class DailyNamingStrategy extends TimestampNamingStrategy {      protected final Logger log = LoggerFactory.getLogger(DailyNamingStrategy.class);     @Override   protected long getTimestamp() {    String dateStr = DateUtil.formatDate(new Date(), "yyyyMMddHH");    return Long.valueOf(dateStr);   }         }  
Copy after login

2.创建CustomWroManagerFactory类

//这个类就是在wro4j-maven-plugin里配置的wroManagerFactory参数  public class CustomWroManagerFactory extends    DefaultStandaloneContextAwareManagerFactory {   public CustomWroManagerFactory() {    setNamingStrategy(new DailyNamingStrategy());   }  }  
Copy after login

上面这两个类的作用是使用wro4j提供的文件命名策略,这样生成的文件名就会带上时间信息了.

例如:basic-2013020217.js

但是现在又会发现一个问题:如果静态资源文件名称不固定的话,那怎么样引用呢?

这时候就需要通过动态生成

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

See all articles