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>
When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.
to avoid xml errors during xhtml validation.
It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.
XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.
You can learn more about CDATA here, and more about XHTML here.
CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript. This is also the reason why JSLint complains about the
<
character in regexes.References
CDATA indicates that the contents within are not XML.
Here is an explanation on wikipedia
HTML
An HTML parser will treat everything between
<script>
and</script>
as part of the script.Some implementations don't even need a correct closing tag; they stop script interpretation at ".</
", which is correct according to the specsSo, in HTML, this is not possible:
A
CDATA
section has no effect at all. That's why you need to writeor similar.
This also applies to XHTML files served as
text/html
. (Since IE does not support XML content types, this is mostly true.)XML
In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.
To the XML parser, a
script
tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by "<
"; and a "&
" sign denotes a character entity.So, in XHTML, this is not possible:
To work around this, you can wrap the whole script in a
CDATA
section. This tells the parser: 'In this section, don't treat "<
" and "&
" as control characters.' To prevent the JavaScript engine from interpreting the "<![CDATA[
" and "]]>
" marks, you can wrap them in comments.If your script does not contain any "
<
" or "&
", you don't need aCDATA
section anyway.