XHTML validation and Javascript : CDATA

With HTML pages on the web you can include the required Javascript betweentags. The W3C validator ignores the Javascript content. The same is not true for XHTML where the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.

The result is a break of the page validation. To fix this problem, one solution is to make the Javascript external to the page. Another solution is to  place the Javascript code within a CDATA tag. However some older web browsers don’t understand the CDATA tag and this breaks the Javascript in those browsers.

If the CDATA tag is commented out, the Javascript code is handled correctly both by newer browsers and by validators and ignored by older browsers and the page is displayed as expected in all cases.

<script type=”text/javascript”>
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>

A guide about this topic has been written by Stephen Chapman on the About.com:Javascript website.