The CDATA blocks were introduced in the XML spec.
They are safe to use today, if you make sure browsers that don't handle them ignore them. This can be donoe through the following:
Code:
<script type="text/javascript">
// <![CDATA[
...
// ]]>
</script>
And for CSS:
Code:
<style type="text/css">
/* <![CDATA[ */
...
/* ]]> */
</style>
The reason for using the CDATA block in XHTML pages:
XHTML is XML, and in XML elements cannot default to CDATA content. Content of elements is ALWAYS parsed, and if it is not well formed, it will cause an error (well, not when sent as 'text/html', but you really shouldn't do that unless the client lacks support for 'application/xhtml+xml'). Since the contents of script and style elements in HTML4.01 was of CDATA type instead of PCDATA type, you could use the characters
< and
& in it freely. That is not the case in XHTML where the contents model is PCDATA. The CDATA block allows you to write any character sequence except
]]> in the contents of the block, without it being parsed as XML. This allows you to use the same characters as you could in the HTML4.01 contents model.
Why you should not use SGML comments:
- XHTML is XML. In XML the content of comments shouldn't be parsed, thus, the script shouldn't run.
- You may not use the
-- character sequence inside a comment in XML.
Browser support:
- If you use the CSS or JavaScript comments like I provided above, the CDATA block can safely be inserted into the document even for browsers that don't support them.
- The browsers that don't handle the CDATA block will choke on the
</ sequence inside a script like they did in HTML4.01, which browsers that support the CDATA block will not.
- Browsers only support the CDATA block in XML ('text/xml' or 'application/xml') or XHTML ('application/xhtml+xml') modes, not in HTML ('text/html') mode.
- All browsers that support XML and/or XHTML mode support the CDATA block.