HTML JavaScript
JavaScript can respond to events and update a page. Load it in a way that keeps the HTML understandable and makes element availability predictable.
How it works
- Use an external script with defer when it should run after parsing while preserving execution order for deferred classic scripts. Modules have their own loading rules.
- Select existing elements and attach listeners rather than placing all behaviour in inline event attributes.
- Use textContent for plain text updates. Inserting untrusted strings with innerHTML can create an injection vulnerability.
A practical example
<button type="button" id="show-message">Show welcome message</button>
<p id="message" role="status"></p>
<script>
document.getElementById('show-message').addEventListener('click', () => {
document.getElementById('message').textContent = 'Welcome to the workshop.';
});
</script>
In a normal page, activating the button updates the status paragraph. The script is placed after the elements so they exist before the selectors run.