css-optimizer is a tool that helps you to remove un-used css rules (extra css rules) basing on sample html files of your website
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Css Optimize Application</display-name>
<context-param>
<param-name>keepClass</param-name>
<param-value>pagination,icon,alert,alert-danger,alert-success,active,voted,invalid,glyphicon,glyphicon-thumbs-down,glyphicon-thumbs-up,voteUp,messages,text-success,hover</param-value>
</context-param>
<context-param>
<param-name>keepTag</param-name>
<param-value>hr</param-value>
</context-param>
<filter>
<filter-name>CssFilter</filter-name>
<filter-class>org.fastercss.cssFilter.CssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>//Step 01.
//Initialize CSSOptimizer with target css file (file will be optimized)
//and output file (result file after optimizing target cssfile)
CSSOptimizer optimizer = new CSSOptimizer("bootstrap.css","bootstrap.min.css");
//Step 02. Sampling your website by downloading web pages or using http urls
optimizer.addHtmlFile("about-us.htm");
optimizer.addHtmlFile("home.htm");
optimizer.addHtmlFile("blog.htm");
optimizer.addHtmlFile("http://your-website.com/product/ipad");
//Step 03. Some classes or tags are added using Javascript code, declare them here:
optimizer.keepClassName("img-thumbnail");
optimizer.keepClassName("pagination");
optimizer.keepTagName("hr");
//Step 04. Execute optimizing,
//result file will be stored in path that is declared in Step 01.
optimizer.optimize();We used css-optimizer to remove un-used css rules in library bootstrap.css.
As the result, 59% rule has been removed, css file size reduced from 121KB to 59KB
and increased about 5 score when testing my site on Google PageSpeed
Please check out and run the test file TestCSSOptimizer.java to see example result
The most important things that i use in this project are Regular Expression and CSS Rule design. I use Regular Expression to split css rules and extract all information about rules and put them into object models (CSSStyleRule, NonCSSStyleRule and CSSMediaRule). Following is class diagram of css-optimizer:
Steps to optimize css file includes:
- Step 1. use jsoup to parse sampling html files and extract all used html tags and css classes
- Step 2. use
Regular Expressionto parse css file and put information into object models - Step 3. compare the result from
Step 1.andStep 2.to get only used css rules and write down them into the result file
Email: [email protected]
Servlet Filter modifications: atramos (github)
The MIT License (MIT)
