Can't run JavaScript in CDATA

Mike Starov picture Mike Starov · Mar 6, 2012 · Viewed 11.7k times · Source

I am trying to run following HTML in every browser: Opera, FF, IE, Chrome

<!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
  <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8">
 </head>
 <body>
  <script>
  <![CDATA[
     alert('Hey!');
  ]]>
  </script>
 </body>
</html>

None of them display the alert. Chrome logs an error in console: Uncaught SyntaxError: Unexpected token <. It seems to be complaining about the fist < in CDATA declaration. Firefox also logs "syntax error"

The w3schools point out that this is the way to use CDATA http://www.w3schools.com/xml/xml_cdata.asp. Other answers on this site suggest it. What am I doing wrong? I tried playing with namespaces and doctypes, but that did not change anything.

Edit: I added XHTML name space and doctype, that I originally removed and the problem still persists.

Answer

danorton picture danorton · Mar 6, 2012

The difference is between HTML and XHTML. W3Schools is correct that it’s a valid CDATA construct within XHTML, but as your question indicates that your code is HTML and there is no such thing as CDATA inside a <script> in HTML, your example fails as soon as the interpreter sees the "<". You can tell the browser that it’s looking at XHTML, but it's probably safer to handle HTML, too. To do that, you need to hide the CDATA inside JavaScript comments. (You might also consider identifying which language is inside your <script> block.)

<html>
 <head>
 </head>
 <body>
  <script>
  //<![CDATA[
     alert('Hey!');
  //]]>
  </script>
 </body>
</html>

This is, in fact, the method recommended by the World Wide Web Consortium (W3C) in XHTML Media Types, A.4. Embedded Style Sheets and Scripts.