Previous Page
Next Page

Where to Put Your Scripts

Scripts can be put in one of two places on an HTML page: between the <head> and </head> tags (called a header script), or between the <body> and </body> tags (a body script). Script 2.1 is an example of a body script.

Script 2.1. Scripts always need to be enclosed inside the <script> and </script> HTML tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>My first script</title>
</head>
<body bgcolor="#FFFFFF">
     <h1>
        <script language="Javascript" type="text/javascript">

          document.write("Hello, world!");

       </script>
    </h1>
</body>
</html>

There is an HTML container tag that denotes scripts, which, as you would guess, begins with <script> and ends with </script>.

To write your first script:

1.
<script language="Javascript" type="text/javascript">

Here's the opening script tag. This tells the browser to expect JavaScript instead of HTML. The language="Javascript" attribute identifies to the browser which scripting language is being used, and the type="text/javascript" attribute tells the browser that the script is plain text, organized as JavaScript.

2.
document.write("Hello, world!");

Here's the first line of JavaScript: It takes the document window and writes "Hello, world!" into it, as seen in Figure 2.1. Note the semicolon at the end of the line; this tells the browser's JavaScript interpreter that the line is ending. With rare exceptions, we'll be using semicolons at the end of each line of JavaScript in this book.

Figure 2.1. The "Hello, world" example is de rigueur in code books. We'd probably lose our union card if we left it out.


3.
</script>

This ends the JavaScript and tells the browser to start expecting HTML again.

Tips

  • There's no need to add language or type attributes to the closing script tag.

  • The language attribute of the script tag has been deprecated in XHTML, which means that the W3C, the standards body responsible for XHTML, has marked the attribute as one that will not necessarily be supported in future versions of the standard. We've used it in this book, but you can choose to skip it in your scripts.

  • Using a semicolon at the end of a JavaScript line is optional, so long as you only have one statement per line. We've included them in this book for clarity, and we suggest that you get into the habit of including them in your code for the same reason.

  • For most of the rest of this book, we've left out the <script> tags in our code explanations. As you'll see from the scripts themselves, they're still there and still needed, but we won't be cluttering our explanations with them.

  • You can have as many script tags (and therefore, multiple scripts) on a page as you'd like.



Previous Page
Next Page