Saturday, September 6, 2014

HTML Minifier using JSP taglib

HtmlCompressor is a small, fast and very easy to use Java library that minifies given HTML or XML source by removing extra whitespaces, comments and other unneeded characters without breaking the content structure.

Bad Practices

  • Don't feed the compressor actual templates (php, jsp, etc). This most likely won't work, even if it does it would be a bad idea anyway as you will lose their readability and further development will be very inconvenient. Instead of compressing templates you should consider compressing resulting html after a template is merged. If you absolutely have to compress templates, you need to set custom block preservation rules for HTML Compressor.
  • If your site is in pure HTML, always keep original files and only compress their copies that will be served to the client. If you compress your only sources, again your further development will be very hard and there is no easy way to decompress pages back. 

Known Issues

  • When <script> tag contains some custom preserved block (for example <?php>), enabling inline javascript compression will fail. Such <script> tags could be skipped by wrapping them with <!-- {{{ -->...<!-- }}} --> comments (skip blocks).
  • Removing intertag spaces might break text formatting, for example spaces between words surrounded with <b> will be removed. Such spaces might be preserved by replacing them with &#20; or &nbsp;.

Compressing selective content in JSP pages

If you install the compressor taglib, you will be able to use <compress:html>, <compress:xml>, <compress:js> and <compress:css> tags in your JSP pages to mark selective code blocks that need to be compressed.

Taglib installation procedure

  1. Download .jar file of the current release and put it into your lib directory
  2. Add the following taglib directive to your JSP pages:
  3. <%@ taglib uri="http://htmlcompressor.googlecode.com/taglib/compressor" prefix="compress" %>
    
Please note that JSP 2.0 or above is required.

Using compressor taglib

Now you can wrap parts of JSP pages that need to be compressed with corresponding tags:

<%@ taglib uri="http://htmlcompressor.googlecode.com/taglib/compressor" prefix="compress" %>
<html>
        Compressor Example
        
                
                        

Header

Link
</html>
Each tag supports all attributes from corresponding compressors, so you have full control over their options, for example:



<compress:js> and <compress:css> tags call corresponding compressors directly bypassing HtmlCompressor, so they should be used only for actual JavaScript and Css content. If you need to wrap mixed content use <compress:html> with required attributes. For the complete list of available attributes see taglib or javadocs.

1 comment: