Skip to content

HTML Tutorial HTML and JavaScript

Where JavaScript Belongs: Placement, defer and async

Lesson 43 of 81 2 min read By Deepak Paswan Updated Oct 4, 2026

Where you put a script, and how you load it, affects how fast your page appears.

The problem

When a browser reads HTML and meets a normal script, it stops, downloads and runs the script, and only then continues. A slow script in the head can leave a visitor looking at a blank page.

Option 1: at the end of the body

Place scripts just before </body>. By then the page content already exists.

index.html
HTML
<body>
  ...page content...
  <script src="app.js"></script>
</body>

defer lets the script download while the page loads and runs it after the HTML is read. You can keep it in the head.

index.html
HTML
<head>
  <script src="app.js" defer></script>
</head>

Deferred scripts run in the order they appear.

Option 3: async

async downloads the script and runs it as soon as it is ready, in any order. It is good for independent scripts such as analytics, and bad for scripts that depend on each other.

AttributeRuns whenOrder kept
noneImmediately, blocking the pageYes
deferAfter the HTML is parsedYes
asyncAs soon as it downloadsNo
warning
Running a script before its elements exist
If your script looks for an element that has not been parsed yet, it gets nothing. Use defer, or place the script after the element.