7

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?

winwaed
  • 7,645
  • 6
  • 36
  • 81
Daniel
  • 199
  • 1
  • 2
  • 7
  • For example, I think some parsers may trip on the less-than and greater-than signs (< and >) in JavaScript code that is not in a CDATA section. – Gintautas Miliauskas Nov 18 '10 at 13:38
  • 2
    This seems to be a duplicate of http://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag . There are some good answers there. – Gintautas Miliauskas Nov 18 '10 at 13:39
  • @Gintautas — parsers *should* trip on them, among other things. Jost's answer is a good one. – Quentin Nov 18 '10 at 13:53

2 Answers2

3

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>
jitter
  • 53,475
  • 11
  • 111
  • 124
  • 1
    Ah okay, so it is the content of the inline script itself that decides whether or not the page is validated, good to know. I think I am going to just start linking to my stuff externally even if it is just a call to a few plugins, it seems cleaner this way. Thanks for the quick reply (Wow!) – Daniel Nov 18 '10 at 13:53
-1

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

winwaed
  • 7,645
  • 6
  • 36
  • 81