Integrate JavaScript on webpages
There are several ways to integrate JavaScript-Code in a webpage: JavaScript integrated directly in the webpage, but in a separate HTML script-tag, an external .js file loaded with a tag, and inline JavaScript which is put directly in other HTML tags. Every method has it's advantages and may be used only under certain circumstances.
First let's take a look at the
Internal JavaScript
This method is good for small to medium sized programs, that are only to be included on a single webpage. For that script tags are used:
<script type="text/javascript">
// JavaScript code goes here
</script>
The type attribute given tells the browser the mime type enclosed by the script tag. Some of you already may have seen such script tags and may wonder about the javascript code being enclosed by further characters inside the script tag.
<script type="text/javascript">
<!--
// JavaScript code goes here
//-->
</script>
or
<script type="text/javascript">
/* <![CDATA[ */
// JavaScript code goes here
/* ]]> */
</script>
The first one is from early browser days when not all browsers knew how to handle the script tags. To prevent the JavaScript program being visible to the user as part of the webpage the programmers enclosed their JavaScript program with HTML multi line comments <!-- (start multi line comment) and --> (end multi line comment, the // is for the JavaScript capable browsers to not interpret the --> as JavaScript code). Nowadays these HTML comments are not needed because all major browsers know about script tags and know how to handle it's content.
The second enclosement is needed if you want to use the script tags in a XHTML page. In HTML the script tag may contain only CDATA (character data), that simply means the content of the script tag is not parsed by the HTML parser. In XHTML standard the script tags may contain PCDATA (parsed character data), that means the XHTML parser trys to interpret characters like <, >, and & which will appear very often in a JavaScript program possibly causing parser errors. To prevent the code being interpreted by the parser you have to declare the content of the script as a CDATA section which is done with the tags <![CDATA[ (open CDATA section) and ]]> (end CDATA section). The JavaScript comments /* and */ are used to prevent the JavaScript interpreter from parsing the CDATA tag.
Another way to prevent the PCDATA issue in XHTML is to use