Why prefer to put JavaScript in the footer of an HTML page?

JavaScript can be placed anywhere in an HTML page, whether inside the <head> or <body> tag. However, it's considered best practice to place JavaScript in the footer, just before the closing </body> tag.

Why Place JavaScript in the Footer?

  • Non-blocking page rendering: Scripts don't block HTML content from loading
  • DOM availability: All HTML elements are already parsed and available
  • Faster perceived load time: Users see content immediately
  • Better user experience: Page appears responsive during script loading
  • Improved performance: Critical rendering path is not interrupted

Example: JavaScript in Head vs Footer

JavaScript in Head (Not Recommended)

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script>
        // This blocks page rendering
        console.log("Script in head executed");
        document.getElementById("myDiv").innerHTML = "Hello"; // Error: element not found
    </script>
</head>
<body>
    <h1>Welcome</h1>
    <div id="myDiv"></div>
</body>
</html>

JavaScript in Footer (Recommended)

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <div id="myDiv"></div>
    
    <script>
        // DOM is ready, all elements available
        console.log("Script in footer executed");
        document.getElementById("myDiv").innerHTML = "Hello World!"; // Works perfectly
    </script>
</body>
</html>

How Browser Loading Works

Head Section Scripts here block page rendering Body Content (HTML Elements) Loads immediately when scripts are in footer JavaScript in Footer - Best Practice Browser Loading Order

Modern Alternatives

While footer placement is still recommended, modern HTML provides additional options:

<!-- Async loading (doesn't block parsing) -->
<script async src="script.js"></script>

<!-- Defer loading (waits for DOM, maintains order) -->
<script defer src="script.js"></script>

Conclusion

Placing JavaScript in the footer ensures faster page rendering and better user experience. This practice remains relevant even with modern async/defer attributes for optimal performance.

Updated on: 2026-03-15T21:21:39+05:30

932 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements