Skip to content
Kuza Ndoto Academy

Adding JavaScript to a Page

Beginner → IntermediateChapter 1 · Page 2 of 324 min readUpdated 15 Nov 2026

Before JavaScript can do anything, the browser has to load it. You add scripts with the <script> element, either by writing code directly in the page or by linking to a separate .js file. Where you place the script, and whether you add defer or async, decides when it runs and whether it can find the elements it needs.

Inline scripts

The quickest way is to write code between <script> and </script> tags inside your HTML. This is handy for tiny experiments and for the examples on this site.

<body>
  <h1>Karibu</h1>
  <script>
    console.log("The page has loaded this script");
  </script>
</body>

You don't need type="text/javascript"; JavaScript is the default. A page can contain several script elements, and the browser runs them in the order they appear.

External JavaScript files

For real projects, put your code in its own file, for example js/app.js, and link it with the src attribute:

<script src="js/app.js"></script>
// js/app.js (no <script> tags inside a .js file)
console.log("Hello from app.js");

External files keep HTML and behaviour separate, let several pages share one script, and can be cached by the browser so returning visitors don't download them again. The file contains only JavaScript; writing <script> tags inside a .js file is a syntax error.

Common mistake

A script element with a src attribute ignores any code written between its tags. <script src="app.js">alert("hi")</script> loads app.js but never runs the alert. Use two separate script elements instead. Also remember the closing </script> tag is required even when the element is empty.

Why placement matters

The browser reads HTML from top to bottom. When it meets an ordinary <script>, it stops building the page, downloads the script if needed, runs it, and only then continues. A script in the <head> therefore runs before the body exists:

<head>
  <script>
    document.getElementById("count").textContent = "5";
  </script>
</head>
<body>
  <p id="count">0</p>
</body>
Uncaught TypeError: Cannot set properties of null (setting 'textContent')

When the script runs, there is no element with the id count yet, so getElementById returns null, and setting a property on null fails. There are two good fixes: put the script at the end of the body, or keep it in the head and add defer.

defer and async

Both attributes tell the browser to download an external script in the background while it keeps building the page. They differ in when the script runs:

  • defer: the script runs after the HTML has been fully parsed, just before the DOMContentLoaded event. Deferred scripts run in the order they appear in the page. This is the best default for your own code.
  • async: the script runs as soon as it finishes downloading, pausing the parser at that moment. Several async scripts can run in any order. Use it for independent scripts, such as analytics, that don't touch your page or depend on other scripts.
<head>
  <!-- your app: waits for the whole page, keeps order -->
  <script src="js/helpers.js" defer></script>
  <script src="js/app.js" defer></script>

  <!-- independent: runs whenever it arrives -->
  <script src="https://example.com/analytics.js" async></script>
</head>
<script> parsing waits defer after parsing async on arrival HTML parsing script download script runs time
Figure 1. A normal script blocks the parser while it downloads and runs. defer and async download in parallel; defer waits until parsing ends, async runs the moment it arrives.
OptionBlocks parsing?Runs whenOrder kept?
<script src> in headYesImmediatelyYes
Script at end of bodyOnly at the very endAfter the content above it existsYes
deferNoAfter parsing finishesYes
asyncOnly while it runsAs soon as it downloadsNo
Note

defer and async only affect external scripts with a src; on an inline script they are ignored. Scripts loaded with type="module" are deferred automatically. You will meet them on the Modules page.

Try it: a script at the end of the body

In the Try-it editor everything must live in one file, so this example uses an inline script placed just before </body>. By the time it runs, the span and button already exist.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Water tracker</title>
</head>
<body>
  <h1>Water tracker</h1>
  <p>Glasses today: <span id="count">0</span></p>
  <button id="add">Add a glass</button>

  <script>
    let glasses = 0;
    const countEl = document.getElementById("count");

    document.getElementById("add").addEventListener("click", () => {
      glasses++;
      countEl.textContent = glasses;
    });
  </script>
</body>
</html>

Try moving the whole <script> element into the <head> and running it again. The button stops working, and the console shows an error because getElementById("add") returned null.

Key points

  • Add JavaScript with <script>, either inline or with src pointing to a .js file.
  • External files are tidier, reusable and cacheable; never put <script> tags inside a .js file.
  • An ordinary script runs immediately and can't see elements that come after it.
  • Use defer (or the end of the body) for your own scripts; use async only for independent scripts.
Up next · Getting StartedThe Console & Debuggingconsole.log, browser DevTools and finding bugs.
→

Tip: use the ← and → keys to move between pages.