How To Use Javascript In HTML Page (Header or Body Section)

Javascript is the default scripting language in HTML. Most of the web programming languages uses Javascript as default scripting language like ASP, PHP etc. Here we will explain the best and optimized way “How to use Javascript in HTML Page“.

In old browsers, we have to show which scripting languages we’re using but now in latest and modern browsers there is no need to put type attribute as shown below.

<script type="text/javascript">

Now type attribute is not required just because Javascript is default scripting language in HTML.

Learn – How To Use getElementById() Method In Javascript

Javascript code must be enclosed with <script></script> tags so that browser can understand. You can place any number of scripts in a single HTML document / page.

How To Inject / Include Javascript In HTML Page

Javascript code can be placed in between <body> section or <head> section or in both.

You can check below examples for more understanding.

Javascript Code In Header Section under <head> Tag

Note: Not recommended to use Javascript code in Header section, it slows down the display/loading of web page.

<!DOCTYPE html>
<html>
<head>

<script>
function cdFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</head>

<body>

<p id="demo">Paragraph At Codedunia</p>
<button type="button" onclick="cdFunction()">Try it</button>

</body>
</html>

Javascript Code In Body Section under <body> Tag

Note: It is recommended to place Javascript code just before the closing of <body> tag. It improve the loading speed of web page because execution of scripts slows down the display of web page.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Paragraph At Codedunia</p>
<button type="button" onclick="cdFunction()">Try it</button>

<script>
function cdFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *