JavaScript Source File
A
lot of JavaScript is incorporated into an HTML document, however
you can also call it from a source file, which is usually designated
with a .js extension. If the JavaScript code is you are writting
is short and it will only be used in the one HTML document,
the just write the code in the document. However, you are writting
an extensive JavaScript, and/or it will be used in Multiple
HTML documents, then you will want to write it in a .js source
file, and call the JavaScript source file. First you need to
know that you do not include HTML tags in a JavaScript source
file, you only include JavaScript in this file. Another possible
reason to use a source file instead of including your JavaScript
in your document would be to hide your JavaScript code. With
your code hidden, it makes it less likely that someone will
steal your code. This is great for script that include passwords
or other sensitive types of scripts. It also makes your HTML
document look much neater and not as cluttered. Creating a
source file also hides your JavaScript from incompatible browsers.
If your HTML document contains JavaScript code, instead of
calling an external JavaScript source file, an incompatible
browser will display the code as if it were standard text.
You
can include embedded JavaScript as well as JavaScript source
files in the same HTML document. To do this however, you do
need to include each JavaScript inside it's own <SCRIPT> tag,
whether it is calling a source file, or embedded in your HTML
document.
You
will include the <SCRIPT>...</SCRIPT> tag pair
in your HTML document, and place the call to the source file
inside the tag utilizing the SRC attribute. For example, to
load a JavaScript Source file that is located in the C:\javafiles\samplesourcefile.js
you would write the code as:
<SCRIPT
LANGUAGE="JavaScript1.2"
SRC="c:\javafiles\samplesourcefile.js"></SCRIPT>
Let's do an example:
First you will need to create a JavaScript Source file, so open
your text editor.
//This
is my first JavaScript Source File
//I am only including one line of code
//This file is named javaScriptSource.js
document.write("This
line was printed from the JavaScript source file.");
|
Now let's generate our HTML document:
<HTML>
<HEAD>
<TITLE>HTML Document with Two JavaScript Sections</TITLE>
</HEAD>
<BODY>
The following line calls an external JavaScript source file.<BR>
<SCRIPT
LANGUAGE="JavaScript"
SRC="c:\javafiles\samplesourcefile.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
document.writeln("This line was created with embedded JavaScript
code.");
document.writeln("This line was also crated with embedded
JavaScript code.");
</SCRIPT>
</BODY>
</HTML>
|
And the results are, Click Here to
find out.
To be continued.......JS book p.33