How to Use External JavaScript File in HTML
To add an external .js
file in a HTML document, use the HTML script
tag and pass the path to the JavaScipt file inside the src=""
attribute.
Typically JavaScript files are included in the head
section of a page, though for efficiency sometimes developers will put them at the end of the page before the closing body
tag.
In the example below, we will include a .js
file located in the same path as the HTML file. It contains a simple alert function that will handle a button onclick
event.
function sendAlert() {
alert('Hello!');
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="app.js"></script>
</head>
<body>
<button type="button" onclick="sendAlert()">Click me</button>
</body>
</html>
Here is the same HTML file except we are including the .js
file at the end of the file to improve loading efficiency:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<button type="button" onclick="sendAlert()">Click me</button>
<script src="app.js"></script>
</body>
</html>
Including JavaScript Files in a Different Location
If you don't know how directory structures work, please read how to use the cd command.
To include a JavaScript file located in a different directory to your HTML file, you will need to supply a path to the file. Here are a few common examples:
<!-- up one directory level from HTML document: -->
<script src="../app.js"></script>
<!-- webroot js folder: -->
<script src="/js/app.js"></script>
<!-- from external location -->
<script src="https://www.examples.com/app.js"></script>
Note – supplying text/javascript
in the type=""
attribute is no longer required:
<script type="text/javascript" src="app.js"></script>