Aral Code

Getting Started Lesson 2 of 30

Where to Put JavaScript — script Tags and External Files

Add JavaScript inside a script tag in the head or body, or in a separate .js file. Learn why scripts usually go at the end of the body or use defer.

JavaScript can live in three places: inside the HTML page in a <script> element, in a separate .js file, or (for tiny things) inside an attribute like onclick. This lesson shows each one and which to use.

Inside a script element

You can put <script> in the <head> or the <body>. The most common place is just before the closing </body> tag.

Example Script at the end of the body
<!DOCTYPE html>
<html>
<body>
  <h1 id="heading">Good morning!</h1>

  <script>
    const hour = new Date().getHours();
    if (hour >= 12) {
      document.getElementById("heading").textContent = "Good afternoon!";
    }
  </script>
</body>
</html>

Why at the end of the body?

The browser reads your HTML from top to bottom. If a script runs before the elements exist, it can't find them.

Example Too early: the script can't find the heading
<!DOCTYPE html>
<html>
<head>
  <script>
    // This runs before the <h1> exists, so it finds nothing.
    const h = document.getElementById("heading");
    document.write("Found the heading? " + (h !== null));
  </script>
</head>
<body>
  <h1 id="heading">Hello</h1>
</body>
</html>

The script prints "false" because the <h1> hadn't been read yet. Putting scripts at the end of the body fixes this.

External JavaScript files

For real websites, put your JavaScript in its own file, such as script.js, and link it with the src attribute:

<!DOCTYPE html>
<html>
<head>
  <title>My Site</title>
  <script src="script.js" defer></script>
</head>
<body>
  <h1 id="heading">Hello</h1>
</body>
</html>

And the file script.js contains only JavaScript, with no <script> tags:

// script.js
document.getElementById("heading").textContent = "Hello from script.js!";

External files have big advantages:

  • HTML and JavaScript stay separate, so both are easier to read.
  • One .js file can be used by many pages.
  • The browser caches (saves) the file, so other pages load faster.

The defer attribute

defer tells the browser: "download this script now, but run it only after the whole HTML is read." That lets you put the <script> in the <head> safely. It's the modern, recommended way for external scripts.

Inline event attributes

You've seen onclick="...". It's fine for learning and tiny demos, but in larger projects it's better to attach events from JavaScript with addEventListener. You'll learn how in the Events lesson.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Where is the most common place for a <script> element without defer?
2. How do you link an external file named app.js?
3. What does defer do?
4. What happens to code written inside <script src="a.js">...</script>?

By Sir Reyel · Last updated 2026-12-04