Alex Rivera | Logout

When is a CDATA section necessary within a script tag?

Asked 2008-09-15T20:52:14.700
976

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>
Edit
Report

3 Answers

24

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.

answered 2010-03-01T19:19:36.257
9

When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.

answered 2008-09-15T20:54:38.267
2

That way older browser don't parse the Javascript code and the page doesn't break.

Backwards compatability. Gotta love it.

answered 2010-03-01T19:19:14.677

Your Answer