JavaScript Where To
The HTML <script> tag is used to embed a JavaScript program in an HTML page. You can place any number of scripts in an HTML document.
Scripts in <body> or <head>
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
Example: Script in <body>
html
<body>
<h2>My First JavaScript</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>Example: Script in <head>
html
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>External JavaScript
Scripts can also be placed in external files. External scripts are practical when the same code is used in many different web pages.
html
<script src="myScript.js"></script>Test Yourself with an Exercise
What is the correct syntax for referring to an external script called 'xxx.js'?