Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

cdata

I'm pretty sure <![CDATA[...]]> sections can be used in XHTML5, but what about HTML5?

like image 264
Darryl Hein Avatar asked Jul 21 '10 18:07

Darryl Hein


People also ask

Can I use CDATA in HTML?

CDATA is Obsolete. Note that CDATA sections should not be used within HTML; they only work in XML. So do not use it in HTML 5.

Is CDATA necessary?

CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript.

Should I use CDATA in XML?

A CDATA section is used to mark a section of an XML document, so that the XML parser interprets it only as character data, and not as markup. It comes handy when one XML data need to be embedded within another XML document. There are two methods to ensure that an XML file is well-formed.

Is CDATA deprecated?

Note: CDATA is now deprecated. Do not use. The CDATA Section interface is used within XML for including extended portions of text.


2 Answers

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 :-)

like image 109
hollsk Avatar answered Sep 21 '22 19:09

hollsk


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".

like image 43
Joel Purra Avatar answered Sep 21 '22 19:09

Joel Purra