HTML and CSS Reference
In-Depth Information
The
src
Attribute
Besides the
language
attribute, the
<script>
tag can also include an
src
attribute, which
allows a JavaScript script stored in a separate file to be included as part of the current
web page. This feature enables you to share JavaScript code across an entire website, just
as you can share a single style sheet among many pages.
When used this way, the
<script>
tag takes the following form:
<script type=”text/javascript” src=”http://www.example.com/script.js”>
The
src
attribute will accept any valid URL, on the same server or on another. Naming
your JavaScript files with the extension
.js
is customary. When you're loading external
scripts in this way, always place the
<script>
tag inside the
<head>
tag.
When JavaScript is included in a page, the browser executes that JavaScript as soon
as it is read. Here's a simple page that includes a script, and the output is included in
Figure 14.1:
Input
▼
<!DOCTYPE html>
<html>
<head>
<title>
A Simple JavaScript Example
</title>
</head>
<body>
<p>
Printed before JavaScript is run
.</p>
<p>
<script type=”text/javascript”>
document.write(“Printed by JavaScript.”);
</script>
</p>
<p>
Printed after JavaScript is run.
</p>
</body>
</html>
14

