Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 0.2 — Adding JavaScript to a Page
JavaScript · Example 1 of 3

A script only sees what is above it

The head script ran before the parser had built the <h1>, so it found nothing (null). The second script came after it.

JavaScript reaches a page through the <script> element, either written inline or loaded from a .js file; where you put it and whether you add defer, async or type="module" decides when it runs and what it can see.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write the head of a page that loads menu.js and then app.js so both run after parsing, with app.js guaranteed to run second.

02

Rewrite the first live example so the head script works without moving it, using DOMContentLoaded.

Explain it without notes

01

What is the difference between a plain script, defer and async?

02

Why does document.getElementById return null when called from a plain script in the head?

03

Why are external script files preferred over inline scripts on real sites?

A script only sees what is above it

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

In the head, the heading is: null
After it in the body: <h1#title>