Sunday, October 18, 2009

How to Write X/HTML Scripts

In the past we were used to write content of HTML page script tags like:

<script>
    <!--
    ...
    //-->
</script>

Browser which didn't understand script tag normally displayed the content of such tag. Wrapping script content to HTML comment prevented such behavior, resulted in skipping the content. Start of HTML comment at beginning is allowed by script interpreter exactly for this purpose and capable browser processed the content of the script tag normally. Be aware that using this technique in XHTML page can lead to skipping the script content as the XML parser can throw away comments while parsing, resulting in empty script element in the DOM.

In XHTML the script tag is defined that it contains #PCDATA content, so XML parser treats it as a markup (characters like <, > have special meaning). Usually you can find such characters in the script as a relational operators. The solution is to wrap the content to the !<[CDATA[ ... ]]> construct, preventing the XML parser to parse the content. However do not forget to wrap CDATA construct into script comments. If you will not do so, the script interpreter will likely throw syntax error exception.

<script type="text/*">
    /* <![CDATA[ */
    ...
    /* ]]> */
</script>

or

<script type="text/*">
    // <![CDATA[
    ...
    // ]]>
</script>

See also: #1 #2.