This blog..

.. is about optimisation that isn't evil.

Removing unused CSS whitespace with ant replaceregexp

If common CSS compressors are not working for you, it may be a more defensive approach to reduce the filesize of a CSS file with simple regular expression replacement. For this example, I chose Apache Ant (using replaceregexp) to shrink the CSS files.

In thisĀ  approach, I remove unused whitespace and linebreaks, but do not alter or optimize the CSS code at all.

Definition of the affected files

For easy reference, we define a fileset.

<fileset id="css.fileset" dir="your-css-folder" includes="**/*.css"/>

Comment removement

Remove comments in one or multiple lines.

<replaceregexp match="/\*.*\*/" replace="" flags="g" byline="true">
<fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="/\*.+?\*/" replace="" flags="gs" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>

Whitespace removement

Multiple whitespace characters are reduced to one, leading/ trailing whitespace is removed.

<replaceregexp match="\s+" replace=" " flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="^\s+" replace="" flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="\s+$" replace="" flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp

Merging of lines

Blocks of CSS statements are collapsed to a single line, multiple line feeds are removed.

<replaceregexp match="\{[\n\r]+" replace="{" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="[\n\r]+\}" replace="}" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="[\n\r]+\{" replace="{" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match=";[\n\r]+" replace=";" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match=",[\n\r]+" replace="," flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="([\n\r])[\n\r]+" replace="\1" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>

This can all be done in a few seconds during compile time.

Performance First Aid: Basics

If your web application suffers from severe slowdowns, these 5 steps will help you to understand the areas of improvement that can have a drastically effect. This is especially true with older applications that didn’t get “web performance” built in by design.
Continue reading Performance First Aid: Basics