When is a CDATA section necessary within a script

2018-12-31 02:52发布

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>

15条回答
听够珍惜
2楼-- · 2018-12-31 03:22

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.

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

查看更多
情到深处是孤独
3楼-- · 2018-12-31 03:24
高级女魔头
4楼-- · 2018-12-31 03:27

CDATA tells the browser to display the text as is and not to render it as an HTML.

查看更多
登录 后发表回答