JavaScript Is More Than You Might Think

  • 6/15/2013

JavaScript placement on your webpage

If you’re new to HTML, all you need to know about it for now is that it delineates elements in a webpage using a pair of matching tags enclosed in brackets. The closing tag begins with a slash character (/). Elements can be nested within one another. JavaScript fits within <SCRIPT> tags inside the <HEAD> </HEAD> and/or <BODY> </BODY> tags of a webpage, as in the following example:

<!doctype html>
<html>
<head>
<title>A Web Page Title</title>
<script type="text/javascript">
// JavaScript Goes Here
</script>
</head>
<body>
<script type="text/javascript">
// JavaScript can go here too
</script>
</body>
</html>

JavaScript placed within the <BODY> tags executes as it is encountered by the browser, which is helpful when you need to write to the document by using a JavaScript function, as follows (the function calls are shown in boldface type):

<!doctype html>
<html>
<head>
<title>A Web Page Title</title>
<script type="text/javascript">
// JavaScript Goes Here
</script>
</head>
<body>
<script type="text/javascript">
document.write("hello");
document.write(" world");
</script>
</body>
</html>

Because of the way browsers load JavaScript, the current best practice for placing JavaScript in your HTML is to position the <SCRIPT> tags at the end of the <BODY> element rather than in the <HEAD> element. Doing so helps to ensure that the content of the page is rendered if the browser blocks input while the JavaScript files are being loaded.

When you’re using JavaScript on an Extensible Hypertext Markup Language (XHTML) page, the less-than sign (<) and the ampersand character (&) are interpreted as XML, which can cause problems for JavaScript. To get around this, use the following syntax in an XHTML page:

<script type="text/javascript">
<![CDATA[
    // JavaScript Goes Here
]]>
</script>

Browsers that aren’t XHTML-compliant don’t interpret the CDATA section correctly. You can work around that problem by placing the CDATA section inside a JavaScript comment—a line or set of lines prefaced by two forward slashes (//), as shown here:

<script type="text/javascript">
//<![CDATA[
    // JavaScript Goes Here
//]]>
</script>

Yes, the code really is that ugly. However, there’s an easy fix for this: use external JavaScript files. In Chapter 2, you learn exactly how to accomplish this simple task.