Placing JavaScript correctly

JavaScript can be placed in a couple of locations within a Hypertext Markup Language (HTML) page: in the <HEAD> </HEAD> section or between the <BODY> and </BODY> tags. The most common location for JavaScript has traditionally been between the <HEAD> and </HEAD> tags near the top of the page. However, placing the <SCRIPT> stanza within the <BODY> section is becoming more common. Be sure to declare what type of script you’re using. Although other script types can be used, because this is a JavaScript book, I’ll declare the following within the opening <SCRIPT> tag:

<script type="text/javascript">

One important issue to note when you use JavaScript relates to pages declared as Extensible Hypertext Markup Language (XHTML). Therefore, JavaScript used within strict XHTML should be declared as follows:

<script type="text/javascript">
<![CDATA[
//JavaScript goes here
]]>
</script>


Older browsers might not parse the CDATA section correctly. This problem can be worked around by placing the CDATA opening and closing lines within JavaScript comments, like this:

<script type="text/javascript">
//<![CDATA[
//JavaScript goes here
//]]>
</script>


When you place the actual JavaScript code in a separate file, you don’t need to use this ugly CDATA section at all. You’ll probably
discover that for anything but the smallest scripts, defining your JavaScript in separate files—usually
with the file extension .js—and then linking to those scripts within the page, is desirable. Here’s a reminder of how you link to a file using the src attribute of the
<SCRIPT> tag:

<script type="text/javascript" src="myscript.js"></script>

No comments:

Post a Comment