Should I use <![CDATA[...]]> in HTML5?

From the same page @pst linked to:

Element-specific parsing for script and style tags, Guidance for XHTML-HTML compatibility: "The following code with escaping can ensure script and style elements will work in both XHTML and HTML, including older browsers."

Maximum backwards compatibility:

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

Simpler version, sort of incompatible with "much older browsers":

<script>//<![CDATA[
   ...
//]]></script>

So, CDATA can be used in HTML5, and it's recommended in the official Guidance for XHTML-HTML compatibility.

This useful for polyglot HTML/XML/XHTML pages, which are served as strict application/xml XML during development, but served as text/html HTML5 in production mode for better cross-browser compatibility. Polyglot pages have their benefits; I've used this myself, as it's much easier to debug XML/XHTML5. Google Chrome, for example, will throw an error for invalid XML/XHTML5 (including for example character escaping), whereas the same page served as HTML5 will "just work" also known as "probably work".


The CDATA structure isn't really for HTML at all, it's for XML.

People sometimes use them in XHTML inside script tags because it removes the need for them to escape <, > and & characters. It's unnecessary in HTML though, since script tags in HTML are already parsed like CDATA sections.

Edit: This is where we open that really mouldy old can of worms from 2002 over whether you're sending XHTML as text/html or as application/xhtml+xml like you’re “supposed” to :-)

Tags:

Html

Cdata