Is CDATA really necessary?

允我心安 提交于 2020-01-14 07:56:06

问题


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?


回答1:


Today it's only really required if you want your XHTML document to be valid. e.g. 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>



回答2:


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



来源:https://stackoverflow.com/questions/4215261/is-cdata-really-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!