3

Recently I've been seeing different ways of wrapping in-line JavaScript:


Option 1:

<script type="text/javascript">//<![CDATA[
    ...
// ]]></script>

Option 2:

<script>
...
</script>

Option 3:

<script type="text/javascript"><!--
...
//--></script>

Option 4: A combination of any of the above?


What is the current standard?

keeg
  • 3,990
  • 8
  • 49
  • 97

1 Answers1

2

HTML5

<script>
alert('Hello world.');
</script>

XHTML

<script type="text/javascript">
//<![CDATA[
alert('Hello world.');
//]]>
</script>

Old Browsers

<script language="javascript"><!--
alert('Hello world.');
//--></script>

The CDATA section in XHTML is required for the document to be parsed as XML.

According to Douglas Crockford, the language attribute is deprecated, and you may use the type attribute instead. In HTML, it is optional. About the HTML comment tag, he has this to say:

Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. <!-- //--> is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.

So, if you are developing a script in a web page for today, you would make use of the HTML5 way.

Ryan Stein
  • 7,930
  • 3
  • 24
  • 38