Where To (Script Tag)
JavaScript Script Tag - Where to Put Code is a core JavaScript concept covering learn how to insert JavaScript into HTML using the script tag, and understand This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
In HTML, JavaScript code is inserted between <script> and </script> tags.
1. Internal JavaScript
You can write JavaScript directly in your HTML file.
<!DOCTYPE html>
<html>
<body>
<h2>Internal Script</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello from Internal JS!";
</script>
</body>
</html>
2. External JavaScript
Scripts can also be placed in external files. External files often contain code to be used in several different web pages.
- File extension:
.js - Benefit: Keeps code organized and allows browsers to cache the script for better performance.
script.js
function myFunction() {
document.getElementById("demo").innerHTML = "Hello from External File!";
}
index.html
<script src="script.js"></script>
Script Placement
You can place the <script> tag in the <head> or at the bottom of the <body>.
Recommended: Bottom of <body>
Placing scripts at the bottom of the <body> element improves display speed, because script interpretation slows down the display.
Modern HTML allows async and defer attributes on external scripts. defer tells the browser to download the script in the parallel but only execute it after the HTML parsing is complete.