Where should I put tags in HTML markup?

JavaScript code in HTML is placed between <script> and </script> tags. You can place them inside the <head>, within the <body>, or just before the closing </body> tag. The recommended approach is placing scripts before </body> so page content loads first.

The <script> tag tells the browser to interpret the content as a script. The type="text/javascript" attribute is optional in modern browsers as JavaScript is the default.

Where to Place <script> Tags In <head> Loads before page renders In <body> Runs where it appears Before </body> Page loads first (best) Placing scripts before </body> is the recommended approach

Syntax

<!-- Inline script -->
<script type="text/javascript">
   // JavaScript code here
</script>

<!-- External script -->
<script type="text/javascript" src="script.js"></script>

The src attribute links to an external JavaScript file, keeping HTML clean and allowing reuse across pages.

Example: Script in <head>

In this example, the function is defined in <head> and called on button click −

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      function greet() {
         document.getElementById("output").innerHTML = "Hello World!";
      }
   </script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <button onclick="greet()" style="padding: 6px 16px;">Click Me</button>
   <p id="output"></p>
</body>
</html>

Example: Script Before </body>

In this example, the script runs after page content loads −

<!DOCTYPE html>
<html>
<head>
   <title>Script at End</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <p id="msg">Original text</p>
   <script type="text/javascript">
      document.getElementById("msg").innerHTML = "Changed by JavaScript!";
   </script>
</body>
</html>

Comparison of Placements

Placement When It Runs Best For
In <head> Before page loads Function definitions, libraries
Before </body> After content loads DOM manipulation (recommended)
External via src Depends on tag position Reusable, cleaner HTML

Conclusion

The <script> tag can be placed in <head> or <body>, but placing it before the closing </body> tag is recommended so page content loads first. For larger projects, use external script files with the src attribute for cleaner and reusable code.

Updated on: 2026-03-16T09:16:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements