Is CDATA really necessary?

I use inline Javascript quite a bit, usually in WordPress themes that I make. I had not heard of wrapping inline Javascript in //<![CDATA[ ... //]]> up until a few months ago, and I have been doing this stuff at a fair level of competency for a few years.

I googled around and I hear that people use this because their Javascript doesn't validate otherwise. I use a strict 1.0 xHTML doctype and have never had a problem validating my markup. Is it because I use jquery, or because usually I only have a few lines of code to activate a plugin? Or is the w3 validator being lenient in this regard? Is there any evidence of functional impact when not using these CDATA markings?


Today it's only really required if you want your XHTML document to be valid. eg something as simple as this is invalid because of the <p> tags in the javascript with the CDATA it validates

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>foo</title>
  <script type="text/javascript">
    alert("<p>Hallo</p>");
  </script>
</head>
<body>
</body>
</html>

I think you are meant to use it to conform to XHTML Strict. otherwise the JavaScript would not be valid XML.

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

上一篇: 如何使用Spring将异常转换为返回码

下一篇: CDATA真的有必要吗?