Are CDATA tags ever necessary in script tags and if so when?
In other words, when and where is this:
<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
preferable to this:
<script type="text/javascript">
...code...
</script>
Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.
When browsers treat the markup as XML:
When browsers treat the markup as HTML:
When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate.
Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:
But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.
This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.
It's an X(HT)ML thing. When you use symbols like
<
and>
within the JavaScript, e.g. for comparing two integers, this would have to be parsed like XML, thus they would mark as a beginning or end of a tag.The CDATA means that the following lines (everything up unto the
]]>
is not XML and thus should not be parsed that way.That way older browser don't parse the Javascript code and the page doesn't break.
Backwards compatability. Gotta love it.
CDATA indicates that the contents within are not XML.