JavaScript Where To
The <script> Tag
In HTML, JavaScript code is inserted between <script>
and </script>
tags.
Example
<script> document.getElementById("demo").innerHTML = "My First JavaScript page"; </script>
JavaScript in <head> or <body>
In HTML, JavaScript can be placed within either the <head> or the <body> section of a document. Each placement has its own advantages and use cases:
JavaScript in <head>
Example
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("dummy").innerHTML = "first javascript pagargaph"; } </script> </head> <body> <h2>Dummy JavaScript in Head <p id="dummy">A Paragraph <button type="button" onclick="myFunction()">Try it</button> </body> </html>
JavaScript in <body>
Placing JavaScript code at the end of the <body> section is a common practice for improving page loading performance: