<script> tag, you can add a short script (in this case, just one line) to a web document, as shown in Listing 4.1. The
<script> tag tells the browser to start treating the text as a script, and the closing
<script> tags. The exception is event handlers, described later in this chapter.
LISTING 4.1 A Simple HTML Document with a Simple Script
<title>The American Eggplant Society
<h1>The American Eggplant Society
<p>Welcome to our site. Unfortunately, it is still under construction.
<p>We last worked on it on this date:
<!-- Hide the script from old browsersdocument.write(document.lastModified);
// Stop hiding the script -->
FIGURE 4.1 Using document.write to display a last-modified date.
In this example, we placed the script within the body of the HTML document. There are actually four places where you might use scripts:
- In the body of the page—In this case, the script’s output is displayed as part of the HTML document when the browser loads the page.
- In the header of the page between the
<head>tags—Scripts in the header should not be used to create output within the
<head>section of an HTML document, since that would likely result in poorly-formed and invalid HTML documents, but these scripts can be referred to by other scripts here and elsewhere. The
- Within an HTML tag, such as
<script>tag. You’ll learn more about event handlers in Chapter 14.
<script>tag. While the .js extension is a convention, scripts can actually have any file extension, or none.
External scripts are supported by all modern browsers. To use an external script, you specify its filename in the <script> tag:
<script> tags—in fact, anything between them will be ignored by the browser.
<script> tags, other HTML tags, or HTML comments. Save the .js file in the same directory as the HTML documents that refer to it.
LISTING 4.2 A Simple Event Handler
"alert('You clicked the button.')"