Course contentsShow
← JavaScript
Lesson 24 of 2,7231. JavaScript FoundationsFree lesson

Script Tag Placement and Loading

Understand where to place scripts in HTML and how placement affects page rendering.

Script Tag Placement and Loading

What you'll learn: Where to put <script> tags in your HTML and why location matters for page performance.

Why Placement Matters

When a browser reads your HTML file, it processes it top to bottom, like reading a book. When it hits a <script> tag, it stops rendering the page to download and run that JavaScript. This is like hitting a pause button on your webpage's appearance.

Think of building a house: if the construction crew stops to install a fancy doorbell before the walls are up, everyone waits around doing nothing. Similarly, if your script loads before the HTML body exists, the page appears blank longer than necessary.

Common Placement Options

In the <head> (Traditional, Not Ideal)

<head>
  <script src="app.js"></script>
</head>

The browser pauses rendering immediately. Users see a blank page while JavaScript loads.

Before Closing </body> (Better)

<body>
  <h1>Hello World</h1>
  <!-- All your HTML content -->
  <script src="app.js"></script>
</body>

The page content loads first, then the script runs. Users see your page faster.

Why Bottom Placement Works

By placing scripts at the bottom, the HTML elements are already loaded when JavaScript runs. This prevents errors (trying to manipulate elements that don't exist yet) and creates a better user experience (content appears quickly).

Key Takeaway: Place <script> tags just before </body> to let your HTML load first, ensuring faster page rendering and preventing JavaScript from trying to interact with elements that don't exist yet.