The head schedules a script with defer, then the body creates the controls that script can safely initialize.

Program

Scripts are resources too. The defer attribute lets a script download while parsing continues, then run after the document is ready.

defer_script.html
Visuals: captured from real browser rendering
<head>
  <script defer src="app.js"></script>
</head>
<body>
  <button id="save">Save</button>
  <p id="status">Waiting</p>
</body>
  1. Schedule script execution for after parsing.

    The script is marked as deferred in the resource state.
    defer keeps parsing moving while the script waits to run.
  2. Load the external script resource.

    The app.js script resource is known but has not run yet.
    The src attribute chooses which JavaScript file the browser loads.
  3. Parse the Save button in the body.

    The Save button appears while the deferred script is still waiting.
    The body can keep building before the deferred script executes.
  4. Parse the initial status message.

    The page shows Save and a Waiting status.
    The status element exists before the deferred script runs.
  5. Run the deferred script after parsing.

    The status updates to Ready after the body is complete.
    A deferred script can safely find and initialize body elements.
defer defer delays script execution until the document has been parsed.
script src The src attribute points to the external JavaScript file.