Should I write my script in the body or the head of the HTML?

In HTML, the script tag can be placed either in the <head> section or in the <body> section. The location affects when the script executes and how it interacts with page elements. Understanding the differences helps you choose the optimal placement for your JavaScript code.

Syntax

Following is the basic syntax for embedding JavaScript in HTML −

<script>
   //JavaScript code here
</script>

You can place multiple script tags in an HTML document, and they can appear in the <head>, <body>, or both sections.

Script in Head Section

When scripts are placed in the <head> section, they are loaded and executed before the HTML body content is parsed. This approach works well for:

  • Function definitions that will be called later by user interactions

  • Global variables and configurations needed throughout the page

  • External libraries that other scripts depend on

However, scripts in the head cannot directly access DOM elements in the body since those elements haven't been created yet.

Example − Script in Head (Function Definition)

<!DOCTYPE html>
<html>
<head>
   <title>Script in Head</title>
   <script>
      function changeText() {
         document.getElementById("sample").innerHTML = "Text changed by head script!";
      }
   </script>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Script in Head Section</h2>
   <p id="sample" style="color: blue;">Original text from TutorialsPoint</p>
   <button type="button" onclick="changeText()">Click to Change Text</button>
</body>
</html>

The function defined in the head works correctly because it's called after the DOM elements exist −

Script in Head Section
Original text from TutorialsPoint  [Click to Change Text]
(After clicking: Text changed by head script!)

Example − Script in Head (Direct DOM Access Problem)

The following example demonstrates why direct DOM manipulation fails when the script is in the head −

<!DOCTYPE html>
<html>
<head>
   <title>Head Script Problem</title>
   <script>
      // This fails because #sample doesn't exist yet
      var elem = document.querySelector('#sample');
      if (elem) {
         elem.style.color = "red";
      } else {
         console.log("Element not found - DOM not ready!");
      }
   </script>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <p id="sample">This text should be red, but it's not!</p>
   <p>Check browser console for error message.</p>
</body>
</html>

This code produces a console message because the paragraph element doesn't exist when the script runs. The text remains in default black color instead of turning red.

Script in Body Section

Placing scripts in the <body> section, especially before the closing </body> tag, ensures that HTML elements are loaded before the script executes. This approach offers several advantages:

  • DOM elements are available for immediate manipulation

  • Faster page rendering since HTML content loads before scripts

  • Better user experience as visible content appears quickly

  • Reduced errors from trying to access non-existent elements

Example − Script in Body (Working DOM Access)

<!DOCTYPE html>
<html>
<head>
   <title>Script in Body</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Script in Body Section</h2>
   <p id="sample">This text will turn red!</p>
   <script>
      // This works because #sample exists above
      document.querySelector('#sample').style.color = "red";
   </script>
</body>
</html>

The script successfully changes the text color to red because the paragraph element exists when the script runs −

Script in Body Section
This text will turn red!  (displayed in red color)

Example − Interactive Script in Body

<!DOCTYPE html>
<html>
<head>
   <title>Interactive Body Script</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Interactive Script Example</h2>
   <p id="content">Welcome to TutorialsPoint</p>
   <button type="button" onclick="updateContent()">Update Content</button>
   <script>
      function updateContent() {
         document.getElementById("content").innerHTML = "Content updated by body script!";
         document.getElementById("content").style.backgroundColor = "yellow";
      }
   </script>
</body>
</html>

The function works correctly and adds both text and styling changes when the button is clicked −

Interactive Script Example
Welcome to TutorialsPoint  [Update Content]
(After clicking: Content updated by body script! with yellow background)
Script Placement Comparison Script in Head ? Functions available globally ? Good for libraries ? DOM not ready ? Blocks page rendering ? Can cause errors Use: Function definitions Script in Body ? DOM elements available ? Faster page rendering ? Better user experience ? Fewer errors ? Functions not global Use: DOM manipulation

Modern Alternatives

HTML5 provides additional control over script loading with the async and defer attributes for external scripts −

Example − Using Defer Attribute

<!DOCTYPE html>
<html>
<head>
   <title>Script with Defer</title>
   <script defer>
      // This runs after DOM is ready, even though it's in head
      document.getElementById("sample").style.color = "green";
      document.getElementById("sample").innerHTML = "DOM ready with defer!";
   </script>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Script with Defer Attribute</h2>
   <p id="sample">Original text</p>
</body>
</html>

The defer attribute ensures the script waits until the DOM is fully parsed −

Script with Defer Attribute
DOM ready with defer!  (displayed in green color)

Best Practices

Here are the recommended practices for script placement −

  • Place scripts before </body> for better page loading performance

  • Use head for function definitions that will be called by user interactions

  • Use body for immediate DOM manipulation and page initialization

  • Consider external scripts with async or defer attributes for advanced loading control

Example − Combined Approach

This example shows the recommended pattern combining both approaches −

<!DOCTYPE html>
<html>
<head>
   <title>Combined Approach</title>
   <script>
      // Function definitions in head
      function toggleColor() {
         var elem = document.getElementById("text");
         elem.style.color = elem.style.color === "red" ? "blue" : "red";
      }
   </script>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Combined Script Approach</h2>
   <p id="text">Click the button to toggle color!</p>
   <button onclick="toggleColor()">Toggle Color</button>
   <script>
      // DOM manipulation in body
      document.getElementById("text").style.color = "blue";
      document.getElementById("text").style.fontSize = "18px";
   </script>
</body>
</html>

This approach provides both immediate styling and interactive functionality −

Combined Script Approach
Click the button to toggle color!  [Toggle Color]  (blue text, 18px)
(Button toggles between red and blue colors)

Performance Comparison

The placement affects page loading performance significantly −

Placement DOM Availability Page Rendering Best Use Case
Script in <head> Not available initially Blocked until script loads Function definitions, libraries
Script in <body> Available immediately Content visible first DOM manipulation, initialization
External with defer Available when script runs Non-blocking Large scripts, multiple files

Conclusion

Place scripts in the <body> section (before closing </body>) for DOM manipulation and immediate execution. Use the <head> section for function definitions and global configurations that will be called later. For external scripts, consider using the defer attribute to combine the benefits of both approaches.

Updated on: 2026-03-16T21:38:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements