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:
And for CSS:
/* <![CDATA[ */
/* ]]> */
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 <
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.
- 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.