To attach an external JavaScript file to the HTML template, we can use the script
tag and then use the src
attribute and define the path to the external JavaScript file inside this attribute.
TL;DR
<!DOCTYPE html>
<html lang="en">
<!--
Define the path to the external
JavaScript code using script tag
and the src attribute
-->
<script src="js/app.js"></script>
<body>
Hello World from HTML
</body>
</html>
For example, first let's write a basic index.html
template which outputs the Hello World from HTML
. It can be done like this,
<!DOCTYPE html>
<html lang="en">
<body>
Hello World from HTML
</body>
</html>
Now let's write the external JavaScript code which logs Hello World from JavaScript
. It cna be done leiek this,
// External JavaScript file with code
console.log("Hello World from JavaScript");
Let's also name this JavaScript file as app.js
and place it under the js
directory or folder. So the structure of both the JavaScript
and HTML
files may look like this,
Current files structure
- index.html
- js
- app.js
Now to include the app.js
file in the HTML file, we can use the script
tag and then use the src
attribute to define the path to the JavaScript file. It can be done like this,
<!DOCTYPE html>
<html lang="en">
<!--
Define the path to the external
JavaScript code using script tag
and the src attribute
-->
<script src="js/app.js"></script>
<body>
Hello World from HTML
</body>
</html>
- **You don't have to write the
script
tag before thebody
tag. You can insert thescript
tag anywhere in the HTML template and it will work. **
Now if you look in the browser console we can see the Hello World from JavaScript
output which shows us that the JavaScript code has been executed successfully.
See the above code live in repl.it.
That's all 😃!