The <script> element is used for load or include executable javascript and data scripts. You will run into it while reading other people’s HTML, and it is useful to know what job it does before copying the code.
What does <script> mean?
Load or include executable JavaScript and data scripts. The tag gives the browser a specific kind of content to work with. It is more helpful to choose a tag for its meaning than because of its default look.
The code attaches a click handler to the button. External classic scripts can use defer; module scripts have their own loading rules.
A working HTML example
Here is a small example you can place in an HTML page and inspect in your browser:
<button id="say-hello" type="button">Say hello</button>
<script>
document.getElementById("say-hello").addEventListener("click", () => {
alert("Hello!");
});
</script>
Reading the example
Find the <script> part first. Notice which elements are around it and how its content or attributes are connected to those other elements.
In this example, <script> appears alongside button or other DOM elements targeted by a script. That context is often just as important as the element itself.
The browser builds its document from these relationships. Any CSS changes appearance, while interactive JavaScript behavior must be provided separately when the example includes it.
When should you use it?
Use <script> when you want to load or include executable javascript and data scripts. A sensible example of this on a real website is the markup shown above; it gives the browser and accessibility tools a clearer job to work with.
Common companions are button or other DOM elements targeted by a script. Check the nesting requirements before moving the element into a different location.
Try it yourself
Change the button label and the alert text; confirm when the script runs.
Common Beginner Mistakes
- Do not put untrusted user text into executable scripts without safe encoding.
- Picking
<script>only because it looks a certain way instead of checking what it means. - Forgetting to inspect the surrounding markup when an element does not behave as expected.
Key Takeaways
<script>helps load or include executable javascript and data scripts.- The code attaches a click handler to the button. External classic scripts can use defer; module scripts have their own loading rules.
- Start with meaningful markup, then add styling or scripting only when the page needs it.