HTML Script Loading: Classic, Defer, Async and Modules
Execute a classic script after markup
A script can contain JavaScript or refer to a resource with src. JavaScript operates on the parsed DOM. The inline classic script below executes as the parser reaches it. getElementById finds an element and textContent changes its text. Place it after the element it needs.
<p id="status">Waiting</p><script>document.getElementById("status").textContent = "Ready";</script>The text becomes Ready before parsing continues.
External scripts and defer
A parser-inserted external classic script without async or defer pauses parsing for fetching and execution. defer allows fetching alongside parsing and runs deferred classic scripts in document order after parsing, before DOMContentLoaded. async instead runs when ready without preserving document order. These attributes do not make inline classic scripts deferred. The data URL below substitutes for a small external script.
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <title>Deferred</title> <script defer src="data:text/javascript,document.getElementById(%27status%27).textContent%3D%27Deferred%27"></script> </head> <body> <p id="status">Waiting</p> </body></html>The external deferred script finds the paragraph despite being declared in head.
Modules and local scope
type="module" selects JavaScript module semantics. Parser-inserted modules without async run after parsing; import and export connect modules, and module bindings are not automatically global properties. This inline module uses const to declare a binding and writes it into the DOM. External modules need appropriate MIME types and cross-origin permissions; use a local HTTP server for separate files.
<p id="result">Waiting</p><script type="module"> const moduleMessage = "Module ready"; document.getElementById("result").textContent = moduleMessage;</script>The paragraph shows Module ready; moduleMessage is not a window property.
Common mistakes and practice
Do not combine async with defer to enforce order; async takes precedence for classic external scripts. Do not assume modules execute immediately, or that placing defer on an inline classic script delays it. When dependencies matter use modules or ordered deferred scripts. A Content Security Policy may block inline scripts; the examples are local teaching snippets.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Script Loading: Classic, Defer, Async and Modules — Knowledge Check
Apply the integration concepts taught in this lesson.
Which attribute loads an external classic script after parsing in document order?
What does async guarantee about independent script order?
What happens with defer on an inline classic script?
Which type selects module semantics?
Why might a script at the start fail to find a later paragraph?