JavaScript Where To

How to Add JavaScript to a Page

JavaScript Where To

Where to put JavaScript — inline in a `<script>` tag, or in an external `.js` file. And where in the HTML it should go.

5 min read Level 1/5 #script-tag#html#external-script
What you'll learn
  • Add JavaScript to an HTML page with the `<script>` tag
  • Link to an external JavaScript file
  • Understand where to place `<script>` (head vs body, defer, async)

In HTML, JavaScript code lives inside a <script> tag. The browser runs the code when it encounters the tag while loading the page.

Inline Script

You can put JavaScript directly inside the HTML:

Inline script index.html
<!doctype html>
<html>
  <body>
    <h1>My First Page</h1>
    <script>
      document.body.innerHTML += "<p>Hello from JavaScript!</p>";
    </script>
  </body>
</html>
▶ Preview: iframe

This works, but mixing logic and markup gets messy fast. For anything beyond a quick experiment, prefer an external file.

External Script

Put your JavaScript in a separate .js file and link to it from the HTML:

<!doctype html>
<html>
  <body>
    <h1>My First Page</h1>
    <script src="app.js"></script>
  </body>
</html>
document.body.innerHTML += "<p>Hello from JavaScript!</p>";

External scripts are easier to read, easier to cache, and easier to share across pages.

Where in the HTML?

The <script> tag can go in the <head> or anywhere in the <body>. But where you put it changes when it runs — which matters because your script needs the elements it touches to already exist.

You can also tell the browser how to load the script using the defer or async attributes:

PlacementWhen it runsRecommended?
<script> in <head>Blocks parsing, runs immediatelyNo — slows down the page
<script> at end of <body>After the page is parsedOld pattern, still works
<script defer> in <head>After parsing, in order✅ Best for most code
<script async> in <head>As soon as it downloads, no order guaranteeFor independent scripts (analytics)
<script type="module">Deferred by default✅ For modern apps

A Complete Example

A minimal page with an external script that runs after the HTML loads:

Complete page with external script index.html
<!doctype html>
<html>
  <head>
    <title>Hello</title>
    <script defer src="app.js"></script>
  </head>
  <body>
    <h1 id="greet">…</h1>
  </body>
</html>
document.getElementById("greet").textContent = "Hello, world!";
▶ Preview: iframe

Up Next

You can now load JavaScript on a page. Next: how to make it show output.

JavaScript Output →