How to add javascript code to the HTML page

By | March 23, 2016

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.


Become an Expert in Programming and Web Development.View all courses!

JavaScript Code

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

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.

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.

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