Welcome to the Hindi Tutor QA. Create an account or login for asking a question and writing an answer.
Pooja in Web Development

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>

2 Answers

0 votes
Nadira

A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10 and a && b instead of i&lt;10 and a &amp;&amp; b, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.

Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.

0 votes
Nadira

When browsers treat the markup as XML:

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

When browsers treat the markup as HTML:

<script>
    ...code...
</script>

When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate.

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

Related questions

...