Chapter 39 of 49

JavaScript Script Loading (defer, async & DOMContentLoaded)

So far, most of our code has simply run from top to bottom. But in a web page, there's an important question we haven't asked yet: when exactly does the browser run your script?

Try this. The script is placed in the <head>, which looks like a tidy place for it:

<!DOCTYPE html>
<html>
<head>
    <script src="app.js"></script>
</head>
<body>
    <h1 id="title">Hello</h1>
</body>
</html>
// app.js
const title = document.getElementById("title");
console.log(title);
title.textContent = "Welcome!";

Console output (Chrome):

null
TypeError: Cannot set properties of null (setting 'textContent')

The heading is right there in the HTML, so why is it null? Because when the script ran, the browser hadn't reached the <h1> yet.

In this chapter, we'll see how the browser reads a page, why scripts can block it, and how the defer and async attributes and the DOMContentLoaded event fix this. These are also very common interview questions.

How the Browser Reads a Page

The browser reads (parses) your HTML from top to bottom, and builds the page's structure as it goes. (This structure is called the DOM; the next chapter is all about it.)

When the parser meets a normal <script> tag, it must stop:

1. Pause reading the HTML
2. Download the script (if it has a src)
3. Run the script
4. Only then continue reading the HTML

Why stop? Because a script can change the page while it's being built, so the browser can't safely continue until the script has finished. This is called a parser-blocking script.

That explains our bug: at the moment app.js ran, the parser had stopped inside the <head>, and the <h1> didn't exist yet.

It also causes a speed problem: if app.js is large or the network is slow, the user stares at a blank screen while it downloads, because nothing below the script has been read yet.


The Classic Fix: Scripts at the End of <body>

The traditional solution is to put scripts just before </body>, as we did in the First JavaScript Program chapter:

<body>
    <h1 id="title">Hello</h1>

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

Now the <h1> already exists when the script runs, and the content is shown before the script blocks anything. This works fine, but it has a weakness: the script can't run until the browser has read the entire HTML, and on older browsers the download didn't even start until the parser reached the end of the page. (Modern browsers scan ahead and often start the download earlier, but you can't control or rely on that.) On a long page, that wastes time.

Modern HTML gives us two better tools: defer and async.


The defer Attribute

A defer script is downloaded in the background while the HTML is parsed, and runs only after the whole HTML document has been parsed, just before the DOMContentLoaded event.

<head>
    <script defer src="app.js"></script>
</head>
<body>
    <h1 id="title">Hello</h1>
</body>

Now app.js from the start of the chapter works, even though it's in the <head>. And because it's in the <head>, the browser starts downloading it immediately.

Deferred Scripts Run in Order

If you have several deferred scripts, they always run in the same order they appear in the HTML, no matter which one finishes downloading first:

<script defer src="library.js"></script>  <!-- big, downloads slowly -->
<script defer src="app.js"></script>      <!-- small, downloads quickly -->

Even if app.js arrives first, it waits until library.js has run. That makes defer safe for scripts that depend on each other, like a library and the code that uses it.

defer Only Works with src

The defer attribute is ignored on inline scripts (scripts without src). This runs immediately, like any normal script:

<script defer>
    console.log("I am NOT deferred, I run right away");
</script>

The async Attribute

An async script is also downloaded in the background, but it runs as soon as it has downloaded, without waiting for the HTML to finish parsing and without waiting for other scripts.

<script async src="analytics.js"></script>
<script async src="ads.js"></script>

Key points:

  • Whichever script downloads first runs first. The order is not guaranteed. ads.js may run before analytics.js.

  • When an async script runs, it pauses the parser for that moment, so the page may only be partly built. Don't rely on elements being there.

  • It may run before or after DOMContentLoaded, depending on how fast it downloads.

  • Like defer, it only applies to external scripts (with src).

So async is perfect for independent scripts that don't touch your page content and that no other script depends on: analytics, ads, chat widgets, performance trackers.


Timelines: Normal vs defer vs async

This picture is the heart of the chapter. "Parse" is the browser reading HTML, "fetch" is downloading the script, and "run" is executing it.

Normal <script> (in the head)
HTML parse : ████░░░░░░░░░░░░░░░░██████████
Script     :     [ fetch ][ run ]
                  ↑ parsing is STOPPED during fetch + run

<script defer>
HTML parse : ██████████████████████████
Script     :     [ fetch ]                 [ run ]
                                       ↑ runs after parsing ends,
                                         in document order

<script async>
HTML parse : ██████████████░░░░░░██████████
Script     :     [ fetch ]  [ run ]
                            ↑ runs as soon as it's downloaded,
                              pausing parsing just for the run

Both defer and async remove the long pause for downloading. The difference is when the script runs: defer waits politely for the page to be ready, async runs the moment it can.

Comparison Table

Feature

Normal <script>

async

defer

Blocks HTML parsing while downloading?

Yes

No

No

When does it run?

Immediately, where it appears

As soon as it's downloaded

After the HTML is fully parsed

Order between scripts

Document order

Not guaranteed

Document order

Can it see the whole page?

Only elements above it

Not guaranteed

Yes

Relation to DOMContentLoaded

Runs before it

Before or after (doesn't wait)

Runs before it (the event waits)

Works on inline scripts?

-

No (ignored)

No (ignored)

Best for

Tiny inline scripts that must run immediately

Independent scripts (analytics, ads)

Your main app code and its libraries

If a script has both async and defer, modern browsers treat it as async. (This combination was used long ago so that very old browsers without async support would fall back to defer.)


Module Scripts Are Deferred by Default

Scripts with type="module" (covered in the Modules chapter) behave like defer automatically: they download in the background and run after parsing, in order. You don't need to add defer (it has no effect on them). You can add async to a module script, and unlike classic scripts, async even works on inline module scripts.

<script type="module" src="main.js"></script>  <!-- deferred automatically -->

The DOMContentLoaded and load Events

Sometimes you can't add defer (for example, inline code in the <head>), but you still want your code to wait until the page structure is ready. For that, the browser fires events that tell you how far loading has progressed.

Event

Fires when

Waits for images?

DOMContentLoaded (on document)

The HTML is fully parsed and all defer and module scripts have run

No. Also doesn't wait for async scripts or iframes

load (on window)

Everything is loaded: images, stylesheets, iframes, async scripts

Yes

You listen for an event with addEventListener(), which takes the event name and a function to run when it happens (the DOM Events chapter covers this in detail):

<head>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const title = document.getElementById("title");
            title.textContent = "Welcome!";
            console.log("Page structure ready");
        });

        window.addEventListener("load", () => {
            console.log("Everything, including images, is loaded");
        });
    </script>
</head>
<body>
    <h1 id="title">Hello</h1>
    <img src="big-photo.jpg">
</body>

Console output:

Page structure ready
Everything, including images, is loaded

The DOMContentLoaded handler can safely use the <h1>. The load event comes later because it also waits for big-photo.jpg.

Use DOMContentLoaded for most setup code (it's earlier, so the page becomes interactive sooner). Use load only when you truly need images or other resources, for example to read an image's real width and height.

document.readyState

The document also has a readyState property that tells you the current stage:

"loading"      → the HTML is still being parsed
      ↓
"interactive"  → parsing is done; defer scripts run, then DOMContentLoaded fires
      ↓
"complete"     → everything is loaded; then the load event fires

This helps with a subtle problem: if your code adds a DOMContentLoaded listener after the event has already fired (for example, in an async script that downloaded late), the listener will never run. The safe pattern is:

function init() {
    console.log("Setting up the page");
}

if (document.readyState === "loading") {
    // Still parsing: wait for the event
    document.addEventListener("DOMContentLoaded", init);
} else {
    // Already parsed: run now
    init();
}

Putting It All Together

Here's a page that uses every kind of script. defer-1.js is a large file and defer-2.js is small. Each script logs a message, plus the current document.readyState. For example, defer-1.js contains:

console.log("defer-1.js runs (" + document.readyState + ")");

The page:

<!DOCTYPE html>
<html>
<head>
    <script>
        console.log("1. Inline script in head (" + document.readyState + ")");

        document.addEventListener("DOMContentLoaded", () => {
            console.log("DOMContentLoaded (" + document.readyState + ")");
        });

        window.addEventListener("load", () => {
            console.log("load (" + document.readyState + ")");
        });
    </script>

    <script defer src="defer-1.js"></script>  <!-- large -->
    <script defer src="defer-2.js"></script>  <!-- small -->
    <script async src="async.js"></script>
</head>
<body>
    <h1 id="title">Hello</h1>

    <script>
        console.log("2. Inline script at end of body");
    </script>
</body>
</html>

Console output:

1. Inline script in head (loading)
2. Inline script at end of body
defer-1.js runs (interactive)
defer-2.js runs (interactive)
DOMContentLoaded (interactive)
load (complete)

And async.js? Its line (async.js runs) appears somewhere in this list, but always before load. Where exactly depends on how fast it downloads, which is exactly what "order not guaranteed" means.

Notice that defer-1.js ran before defer-2.js even though it's larger and finished downloading later. Deferred scripts keep their order.


Scripts Added from JavaScript

You can also create a script tag from code, for example to load a widget only when it's needed:

const script = document.createElement("script");
script.src = "chat-widget.js";
document.head.append(script);

Scripts added this way behave like async by default: they don't block the page and run in whatever order they finish downloading. If you need several dynamic scripts to run in insertion order, set script.async = false on each one before adding it. (You'll learn createElement() and append() in the next chapter.)


Which One Should I Use?

Does the script need the page's HTML, or depend on / get used by other scripts?
    YES → defer (or type="module", which is deferred automatically)
    NO, it's fully independent (analytics, ads) → async

Is it tiny inline code that must run before the page shows (e.g. setting a theme)?
    → normal inline <script> in the head

Working with old code that has scripts in the head without defer?
    → wrap the code in a DOMContentLoaded listener, or move the script to the end of body

A good modern default: put your scripts in the <head> with defer. Downloading starts early, nothing blocks, and the page is fully parsed when your code runs.


Common Mistakes

  • Accessing elements from a normal script in the <head>. They don't exist yet, so you get null and a TypeError. Use defer or DOMContentLoaded.

  • Using async for scripts that depend on each other. If app.js uses a library loaded with async, it might run before the library and crash. Use defer to keep the order.

  • Adding defer or async to inline scripts. They are ignored there (except async on module scripts).

  • Using load when DOMContentLoaded is enough. load waits for every image, which can be seconds later.

  • Adding a DOMContentLoaded listener too late. If the event already fired, the listener never runs. Check document.readyState first.

  • Wrapping deferred code in DOMContentLoaded "to be safe". It's harmless but unnecessary: deferred scripts already run after parsing.


Interview Tips

A good short answer to "What's the difference between async and defer?":

"Both download the script in parallel without blocking HTML parsing, and both only work on external scripts. A defer script runs after the HTML is fully parsed, in document order, before DOMContentLoaded. An async script runs as soon as it's downloaded, in no guaranteed order, and may run before or after DOMContentLoaded. I use defer for app code and async for independent scripts like analytics."

Other favourites:

  • "DOMContentLoaded vs load?" DOMContentLoaded fires when the HTML is parsed (and deferred scripts have run); load waits for all resources such as images.

  • "Why was the advice to put scripts at the bottom of <body>?" Normal scripts block parsing, and elements below them don't exist yet. defer in the head is the modern alternative.

  • "Are module scripts blocking?" No, they are deferred by default.

  • "What if a script has both async and defer?" Modern browsers use async.

Practice: for a page with <script defer src="a.js">, <script src="b.js"> and <script defer src="c.js"> in the head (in that order), write down the order in which a.js, b.js, c.js and DOMContentLoaded happen. (Answer: b.js, a.js, c.js, then DOMContentLoaded.)

Conclusion

Where and how you load a script decides when it runs and whether it can see the page.

  • A normal <script> stops HTML parsing while it downloads and runs, and can only see elements above it.

  • defer downloads in the background and runs after parsing, in order, before DOMContentLoaded.

  • async downloads in the background and runs as soon as it's ready, in no guaranteed order.

  • Module scripts are deferred automatically.

  • DOMContentLoaded means the HTML is ready; load means everything, including images, is ready.

  • Modern default: <script defer src="..."> in the <head>.

Now that we know our code can safely reach every element on the page, the next chapter shows how to select and change those elements with DOM manipulation.