Command Palette

Search for a command to run...

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

The order of plain, inline and deferred scripts

The examples can't load separate files, so the external scripts use data: URLs (the file's text written into the address). A real page writes src="app.js".

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?

The order of plain, inline and deferred scripts

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

1. plain external file in the head
2. inline script at the end of the body
3. deferred external file
4. DOMContentLoaded: the DOM is complete