HTML and CSS Reference
In-Depth Information
1.11.1 JavaScript from External Files
When scripts are long or need to be shared by other pages, they are usually placed in
external files, separate from the HTML page. Keeping the JavaScript separate (unobtru-
sive JavaScript) from the HTML or CSS files is important when developing a Web site.
It enables you to apply one set of functions to every page of the site, so that when you
need to make a change, you can do it in one document rather than going through each
individual page to apply the change. A JavaScript external file contains just plain Java-
Script code and is saved as a .js file. The .js file is linked to the Web page by including it
between the <head> tags of the HTML document and within its own <script> tags. The
external JavaScript file is assigned to the src attribute of the <script> tag in the HTML
file. The external file name includes the full URL if the script is on another server, direc-
tory path or just the script name if in the local directory. You can include more than one
.js script in a file.
<script type="text/javascript"
src=" http://servername/JavaScriptfile.js" >
</script>
The following examples, although very small, give you the idea of how external files are
used. The welcome.js script contains a JavaScript function (see Chapter 7, “Functions”).
EXAMPLE 1.6
// The external file called "welcome.js"
function welcome(){
alert("Welcome to JavaScript!");
}
EXAMPLE 1.7
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>External .js File</title>
1
<script type="text/javascript" src="welcome.js">
2
</script>
</head>
<body bgColor="lavender">
We are working with an external file.<br />
3
<input type="button" onClick="welcome()" value="Welcome Me!" />
</body>
</html>
 
 
Search WWH ::




Custom Search