The Correct Syntax for the inline <script> tag.

HTML

In HTML, the content type between the <script> tags is treated as CDATA which means that entities enclosed within it will not be parsed.

<script type="text/javascript">
// Your unescaped Javascript here...
</script>

Note: It is no longer necessary to enclose the contents in comment tags i.e. “// <!–  (Javascript here)  //–>”. This was once a common practise in order to hide the Javascript from very old browsers which didn’t recognise Javascript and would attempt to display it as text. Since the demise of Mosaic, Netscape 1 and Internet Explorer 2 circa 1996 this is no longer an issue.

XHTML

In XHTML, the content between the <script> tags is treated as #PCDATA which means that it will be parsed. So, to avoid having to encode the data between the tags we enclose it in a CDATA section.

Some older browsers don’t recognise the CDATA tag so we “hide” them by prefixing them with Javascript comments “//”.

The end result is that the page will validate as XHTML and will still work in older browsers.

<script type="text/javascript">
//<![CDATA[
// Your unescaped Javascript here...
//]]>
</script>

Note: In either case, we no longer use the deprecated “language” attribute.

Advertisements