Monday, June 17, 2019

External JavaScript Files

External JavaScript Files
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:

Click Me!

No comments:

Post a Comment