HTML JavaScript
Write a deferred script reference to an app.js file.
Understand the topic
JavaScript can read the DOM, respond to events, and change content. A script can be inline or loaded with src. External classic scripts commonly use defer so parsing can continue and the DOM is ready before the script runs. Prefer event listeners to inline event attributes, and keep a page useful before adding optional interactive behavior.
Worked example
<button type="button" id="count">Add one</button>
<output id="total" aria-live="polite">0</output>
<script>
let total = 0;
document.querySelector("#count").addEventListener("click", () => {
document.querySelector("#total").textContent = String(++total);
});
</script>
The variable stores the count and the output displays it. Each click changes the state and updates the DOM.
Practice
Write a deferred script reference to an app.js file.
Show a suggested answer
<script src="app.js" defer></script>Common mistake
A script that queries elements before they exist can receive null. Use defer or place the script after its required elements.