External JavaScript Files (JavaScript Tutorial part 5)

১১/১৯/২০১১ ০৮:০১:০০ AM | , | 0 comments »

Having already discussed placing JavaScript in the head and body of your HTML document, let us now explore the third possible location type -- an external file. If you have ever used external CSS before, 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 file 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 the HTML file we are going to code up. To import the file you would do the following in your HTML document.

File myjs.js Contents:

function popup() {
alert("Hello World")
}

HTML & JavaScript Code:

<html>
<head>
<script src="myjs.js">
</script>
</head>
<body>
<input type="button" onclick="popup()" value="Click Me!">
</body>
</html>

Display:

Great JavaScript Repositories

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.

External File Tips & Recap

  • 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 contain HTML commenting and JavaScript code -- nothing more!