1

In the beginning of a block of HTML, I found this:

<body><script type="text/javascript" language="javascript1.2">//<![CDATA[
<!--
     ...a bunch of if/thens that drive a browser specific line of text...
//-->
//]]></script>

I'm confused because I would expect the HTML and javascript comment tags <!-- --> and // to prevent the code from running, in essence parsing to

<body><script type="text/javascript" language="javascript1.2"></script>

However, I'm getting the browser-specific text displaying and there doesn't seem to be anyplace else that it's being generated. Does the <![CDATA[ somehow override the javascript comment, allowing the script to run, while the HTML comments inside the CDATA block are preventing the javascript from displaying in the browser? Can someone help me understand how this all gets parsed and displayed/used?

dwwilson66
  • 6,806
  • 27
  • 72
  • 117

2 Answers2

1

<!-- --> is only used for HTML comments, not for javascript comments. Javascript uses // for single-line and /* */ for multi line comments. If you do use <!-- --> in javascript it would normally just be ignored. Some browsers may throw a javascript error on it.

wvdz
  • 16,251
  • 4
  • 53
  • 90
1

First, all JS code is put here inside CDATA section (see Wikipedia). That's why there are comments //<![CDATA[ and //]]>. That allows to write arbitary characters inside JS code, including characters, which are considered as special symbols for XML, like '<', '>', etc.

HTML comment start <!-- denotes a start for single comment in JavaScript (see this article). HTML comment end - --> has no meaning in JavaScript, that's why it is preceded by //.
HTML comments are used here to hide JavaScript code from browsers, which do not support JavaScript. For that browsers, the code will be just a text between <!-- and --> and will not be displayed on a page.
Commenting in a such way is a very old practice.

In any case, the best is to have all JavaScript code in a separate file and to include that file using <script> tag. That way one will avoid using both CDATA and HTML comments.

bhovhannes
  • 5,511
  • 2
  • 27
  • 37