How to use JavaScript in an HTML document

Share

JavaScript in HTML

To add interactiveness to a web page, we use the JavaScript <script></script> tag and include it in the HTML file.

The location of the JavaScript element in the HTML file can be either in the head or body tag

Example

We can place the <script></script> tag in the <head> and <body> section of an HTML file, as shown in the image below:

Placing the script tag in an HTML file
Placing the script tag in an HTML file

However, if we run different functions, it is best to put the <script></script> tag in the body section before the </body> closing tag. This ensures that the webpage loads faster.

Putting the script tag in an HTML file

External JavaScript file

We can place the JavaScript codes in another file with the .js extension. The JavaScript file should then be linked with the src attribute.

In the example below, we create files in the src folder with the .js extension:

 Creating different files to link in VS Code
Creating different files to link in VS Code

To link the JavaScript file to the HTML file, we need to input the code <script src="src/app.js"></script> in the </body> section of our HTML file before the closing tag. Let’s look at an example below:

Linking an HTML file and a JavaScript file
Linking an HTML file and a JavaScript file
<html>
 <head>
 </head>
 <body>
    Hello World
    <script src="src/app.js"></script>
  </body>
</html>
Complete implementation of JavaScript in an HTML file