HTML and CSS Reference
In-Depth Information
The stringReverse() function has already been entered for you and stored in a file
named spam.js . To access JavaScript code and functions placed in external files, you
employ the same script element you use to insert JavaScript commands directly into a
document. The code to access an external script file is
<scriptƒsrc=” url ”ƒtype=” mime-type ”></script>
where url is the URL of the external document and mime-type is the language of the
code in the external script file. For example, to access the code in the spam.js file, you
would add the following script element to your Web document:
<scriptƒsrc=”spam.js”ƒtype=”text/javascript”></script>
It's a common practice for JavaScript programmers to create libraries of functions
located in external files that are easily accessible to pages on the entire Web site. Any
new functions added to the external file are then instantly accessible to each Web page
without having to edit the contents of those pages. External files containing JavaScript
commands and functions always have the file extension .js to distinguish them from files
containing script commands from other languages.
When a browser encounters a script element that points to an external file, it loads
the contents of the external file into the Web document just as if the programmer had
entered the code from the external file directly into the Web file. See Figure 10-21.
Place all script elements
that reference external
files in the document head
so that those programs
are immediately loaded by
the Web browser and can
be referenced by any code
within the Web page.
Figure 10-21
Using an external script file
script element t o load the
contents of the spam.js file
spam.js
Accessing an External JavaScript File
• To access the code stored in an external file, add the script element
<scriptƒsrc=” url ”ƒtype=” mime-type ”></script>
to the Web page, where url is the URL of the external document and mime-type is
the language of the code in the external script file.
• For JavaScript files, set the mime-type to text/javascript .
You'll insert a script element into the staff directory page to access the code from
the spam.js file.
To access the code in the spam.js file:
1. Return to the mpl.htm file in your text editor.
2. Directly below the link element in the head section of the document, insert the
following script element, as shown in Figure 10-22:
<scriptƒsrc=”spam.js”ƒtype=”text/javascript”></script>
Search WWH ::




Custom Search