How to add JavaScript to HTML - To include an external JavaScript file, we can use the JacaScript's script tag with the attribute src. The src attribute helps to give the path to the script file. In HTML, JavaScript code must be inserted between <script> and </script> tags.
There are three ways to add JavaScript to a web page:
Placing the JavaScript code directly inside an HTML tag with events.
Embedding the JavaScript code between a pair of <script> and </script> tag.
Creating an external JavaScript file with the .js extension and then load it within the page through the src attribute of the <script> tag.
Tip : The type attribute for <script> tag (i.e. <script type="text/javascript">) is no longer required in HTML5.
JavaScript is the default scripting language for HTML5.
Tip : Placing scripts at the bottom of the <body> element improves the loading time of the webpage, because script compilation increases the loading time of the page.
JavaScript in Head Section
You can also add JavaScript in head section same like body section.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript in Head Tag </title>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Output
JavaScript in Head Tag
A Paragraph
External JavaScript
JavaScript code can also be added from a separate file with a .js extension, and
then you can add that file in your document through the src attribute of the <script> tag.
It is useful when you want to use the same script in multiple documents.
Tip : It is recommended to separate the content and structure of your web page (i.e. HTML) from presentation (CSS), and behavior (JavaScript).
Syntax
<script src="js/file.js">
JavaScript File
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Add External File </title>
</head>
<body>
<h1>External JavaScript</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>