main banner

Development

Facelets - JavaScript Parsing

One of the most common issues when starting a project for the 1st time with FACELETS (XHTML + XML) is that it does not handle very well JAVASCRIPT enclosed in a normal <SCRIPT> tag within the JSF file.

The reason behind this is that XML has five special characters which have a special treatment by the XML parser:

• < the start of a tag.

• > the end of a tag.

• “ the start and end of an attribute value.

• ' the alternative start and end of an attribute value.

• & the start of an entity (which ends with ;).


For example the following block of code would result in an exception thrown by the XML parser:

Blog Article

Exception thrown:

Blog Article

In order to fix that problem you would need to escape all the XML special characters which would result in the following code:

Blog Article

As you may see now, these makes the JavaScript code harder to read and even harder to maintain, however there are two approaches to deal with this without the need of escaping special characters:

1. CDATA Block.


You can place your JAVASCRIPT in a character data block (CDATA). Basically what this does is parsing your JAVASCRIPT code as simple vanilla character data instead of XML characters.

Your code would look like this:

Blog Article

2. Put your JavaScript in its own file.


Another option, and a much better one if you ask me, is to put the JavaScript code on its own external file and only include the file in your JSF.

Blog Article

By doing this, you will avoid the need of escaping XML characters or putting a CDATA reference in your JAVASCRIPT code, also it is a pretty good practice since you should not clutter your JSF with JavaScript code.


References:

• Predefined entities in XML:

https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML

• Writing JavaScript for XHTML

https://developer.mozilla.org/en-US/docs/Archive/Web/Writing_JavaScript_for_HTML



Luis M.

Luis is a Software Engineer with more than 10 years of experience in the Software Development sector. He was born in Monterrey, Mexico and some of his favorites things in life are playing videogames, reading about history & running like there is no tomorrow!.. Some say he is the prince that was promised but maybe Melisandre & Jon Snow disagree on that. He is proud to be part of the Inflection Point blogger crew.


Articles