Dot Net For All

How to add JavaScript code to the HTML page

This is a very basic article for the beginners, to let the developer know where in the HTML we should place the JavaScript code. While writing the JavaScript as a beginner programmer, most of the time developer doesn’t know where to write the JavaScript code and they spend too much time looking for the solution for it.

JavaScript Code

The JavaScript code is usually enclosed in the script tag in the HTML page. as shown below

<script>
var myVar = "Hello World";
alert(myVar);
</script>

In the above example I have created a JavaScript code snippet where I have declared a variable named myVar and shown it in the alert which will in turn display a message box when we load the HTML page.

We can place this script based on the need, about when do we want to execute this code. If we want to execute this code before loading the whole of the HTML of the web page in that case this code should be placed in the <Head> section of the HTML page as shown below code.

<html lang="en">  
<head> 
 <script> 
  var myVar = "Hello World"; 
  alert(myVar); 
 </script> 
 <title>Page Title</title> 
 </head> 
 <body> <p>This is the web page</p> </body> </html>

Now before execution of this code we should be aware that the execution of the HTML page is sequential from the Top to bottom of the page.

If we want to execute the JavaScript code after the rendering of the HTML in that case we can keep the code after the body tag of the HTML page as shown in the below code snippet.

<html lang="en"> 
 <head> 
  <title>Page Title</title> 
 </head> 
 <body> 
 <p>This is the web page</p> 
 </body> 
 <script> 
   var myVar = "Hello World"; 
   alert(myVar); 
 </script> 
</html>

The other  way to include the JavaScript code in the HTML file is to add a separate JavaScript file with .js extension to the folder. And add the file’s reference to the html code as shown below:

<!DOCTYPE html> 
<html> 
 <head> 
  <script src="script.js"></script> 
 </head> 
 <body> 
  <h1>Hello Plunker!</h1> 
 </body> 
</html>

This was a basic article for the beginners to help them to know about the JavaScript code.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview