HTML and CSS Reference
In-Depth Information
Listing 3-5 shows a short bit of JavaScript embedded in a document's header. This script simply generates
an alert dialog as soon as the page loads; not very useful, but it serves as an adequate demonstration.
Listing 3-5.
A simple script embedded in a
script
element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Power Outfitters Superhero Costume and Supply Co.</title>
<script>
window.onload = function() {
alert("Excelsior!");
}
</script>
</head>
<body>
<h1>Welcome, Heroes!</h1>
<p>Power Outfitters offers top of the line merchandise at
rock-bottom prices for the discerning costumed crime-fighter.</p>
</body>
</html>
Somewhat akin to the
style
element, a
script
element can embed scripts directly into the document for
use within that document alone. But the
script
element can also attach an external script by way of the
optional
src
attribute (short for “source”), the value of which is the URL where the external script can be
found, usually with a
.js
file extension for JavaScript files.
Listing 3-6 shows a
script
element with a
src
attribute pointing to an external file. This allows any
number of pages to share the same resources without writing the same scripts over and over for each
page. It can also help pages load faster because the external files are cached after the first time they're
downloaded, held in the browser's temporary memory for use on subsequent pages.
Listing 3-6.
Linking to an external script file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Power Outfitters Superhero Costume and Supply Co.</title>
<script src="/scripts/excelsior.js"></script>
</head>
<body>
<h1>Welcome, Heroes!</h1>
<p>Power Outfitters offers top of the line merchandise at
rock-bottom prices for the discerning costumed crime-fighter.</p>
</body>
</html>
When the
src
attribute is present the
script
element must be empty (it can still contain whitespace or
comments, but no script statements). This means you can't use the same script element to both embed a