miércoles, 5 de diciembre de 2012

HTML white space compression for JSF using MyFaces and Facelets

In MyFaces Core another nice feature was introduced since version 2.1.10. The idea is quite simple, just try to minimize the additional white spaces in a html page to reduce its size. Usually the code generated by renderers does not contains unnecessary spaces, but the code that comes directly from html markup in facelets comes straight from the xhtml or xml file used.

The trick behind this feature is enable/disable it as a do inside facelets compiler option. Just add this into your WEB-INF/faces-config.xml  file:


<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
                         version="2.1">
<faces-config-extension>
    <facelets-processing>
        <file-extension>.xhtml</file-extension>
        <process-as>xhtml</process-as>
        <oam-compress-spaces>true</oam-compress-spaces>
    </facelets-processing>
</faces-config> 


That's it. Now, facelets compiler will try to reduce or remove spaces/tabs when they are not necessary, following the rules for html white space compression, to avoid change the apperance of the page. In simple words, this means when necessary it replace multiple continuous spaces with just one or remove all of them. It also try to use '\n' characters when possible, to make easier read the page markup once compressed.

Since this optimization is done in facelets compiler, the effort to reduce white spaces is just done once, so all your pages will not impose additional CPU or memory overhead. It's more, it reduce the memory and CPU resources required to render a page, so this can give a little boost to your application.

Note this only affects the spaces generated by plain html markup, if you have a component renderer that output some spaces, those ones are not preprocessed.