A little tip about how to comment javascript and html files in JSF and JSP

It is a common practice to comment javascript functions. And it’s a good thing, of course.

But to expose those comments in your final production-deployed web app is not a good thing. It will increase the exposure of the code, and may cause some network performance issues.

In JSF 2, you can remove ALL HTML comments, by adding this to your web.xml:

<context-param>
    <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
    <param-value>true</param-value>
</context-param>

And, of course, you can remove them one by one by using <ui:remove>.

Notice that this will NOT remove javascript comments inside the view files. You should use <ui:remove> for them, or consider not use javascript inside your views and to apply a compressor on those .js files (see below).

If you’re using JSP, one thing you can do (and this is the approach I prefer) is to use scriptlet comments. According to the Java Server Pages code conventions, you can use scripting language comments:

<script type="text-javascript">
    <%
    /**
     * My function. This is my function and it does something.
     *
     * @param el this is a param
     * @author bluefoot
     */
     %>
    function myFunction(el) {
        // implementation
    }
</script>

This is following some JSDoc conventions. It might help you since some IDEs can understand that. And, of course, following conventions is always good.

Futhermore, the article exposes what it calls pure JSP comment:

<script type="text-javascript">
    <%--
     My function. This is my function and it does something.

     @param el this is a param
     @author bluefoot
     -- %>
    function myFunction(el) {
        // implementation
    }
</script>

Well, I don’t use this last approach. For HTML comments inside JSP files, I use standard inline scriptlet comment:

<%-- this is a comment. the user will not see it --%>

What about comments inside .js files?

Those files must be treated as resources, and (by default) they are not processed by any server-side language or script. What I strongly recommend is to use a javascript compressor, which will remove comments, whitespaces alongside dozen of other optimizations for deployment and production use. The most popular compressors are YUI Compressor, Closure Compiler and Packer.

Summarizing

Lets put it all together:

LanguageHTML commentsJavascript inside view commentsJavascript in .js resource files comments
jsp/jstlinline scriptletScripting language commentscompression tool
faceletscontext param in web.xmlui:removecompression tool
in Java | tags , , , ,

Leave a Reply