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.

Removing unused whitespace with mod_substitute

Unnecessary whitespace comes from many sources: It’s added from developers to have a readable code (required!), it’s added from frameworks (oh well), it’s added from auto-formatting and saving rules of your ide (and 4 tabs may end as 32 spaces), and maybe it’s added from other tools in your development chain. In the development cycle whitespace is important, but when the page is delivered it’s unnecessary. So let’s get rid of it with mod_substitute.
Continue reading Removing unused whitespace with mod_substitute