Having already dicussed placing Javascript in the head and body
of your HTML document, let us now explore the third possible location, an external
file. If you have ever used external CSS this lesson will be a cinch.
Importing an External Javascript File
Importing an external file is relatively painless. First the file you are importing
must be valid Javascript, and only Javascript. Second, the file must have the extension
".js". Lastly, you must know the location of the file.
Let us assume we have
a file "myjs.js" that contains a one line Hello World alert function. Also, let us
assume that the file is the same directory as our HTML file we are going to code up. To import the file
you would do the following in your HTML document.
There is a ton of great stuff you can do with Javascript, if you know how to code
like Paul Allen and Bill Gates, but for the rest of us it is nice to get incredible Javascript
tools without having to write them ourselves. Below are some of the better Javascript
resources on the web these days.
Use external Javascript files when you want to use the same script on many pages, but
don't want to have to rewrite the code on every page!
Use external Javascript files for including both types of scripts! The type that you place
in the head (functions) and the type you place in the body (scripts you want to
run when the page loads).
Be sure that your Javascript files (.js) do not include the <script> tag. They should
only have the HTML comment and Javascript code.