Daniel
Daniel

Reputation: 199

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?

Upvotes: 7

Views: 2609

Answers (2)

jitter
jitter

Reputation: 54605

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>

Upvotes: 3

winwaed
winwaed

Reputation: 7801

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

Upvotes: -1

Related Questions