When is a CDATA section necessary within a script tag?

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>

A CDATA section is required if you need your document to parse as XML (eg 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 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.

For a good writeup on the subject, see http://javascript.about.com/library/blxhtml.htm


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>

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

Update In HTML5, and with current browsers, that is not the case anymore.

So, in HTML, this is not possible:

<script>
var x = '</script>';
alert(x)
</script>

A CDATA section has no effect at all . That's why you need to write

var x = '<' + '/script>'; // or
var x = '</script>';

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

<script>
if (a<b && c<d) {
    alert('Hooray');
}
</script>

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 a CDATA section anyway.

链接地址: http://www.djcxy.com/p/18976.html

上一篇: HTML 5与XHTML 1.0 Transitional?

下一篇: 在脚本标记中何时需要CDATA部分?