The script element brings JavaScript into a document. A separate script file keeps behavior easier to manage as the site grows.
What You Need to Know
The defer attribute lets a classic external script wait to run until the document has been parsed, preserving its order with other deferred classic scripts. A button still needs JavaScript code to act.
Defer normally preserves order for classic external scripts and waits until parsing ends. Async executes when ready, which can change ordering.
Think of an HTML document as a small book: the browser needs a title and some information about how to read it, while visitors need the actual chapters and text.
Example: See It in Action
Add this example to the appropriate part of a practice HTML page. Read each line before you open the page in your browser.
This is a short HTML fragment. To try it as a webpage, put it inside the body element of a complete HTML document.
<script defer src="scripts/site.js">
</script>
<main>
<h1>Script Loading</h1>
<button type="button" id="greet">Say hello</button>
</main>
Let’s Understand the Example
- A script adds JavaScript or declares another kind of script data. HTML alone does not run most interactive behavior.
- Main identifies the central content of the page; it should not be duplicated as separate visible main landmarks.
- An h1 introduces the main subject of the page. Use the heading level for structure rather than font size.
- Src tells the browser where to find an image or other embedded resource.
- Type changes the kind of input, script, resource or button, depending on the element.
- Id gives one element a unique name within the page, so a link, label, or script can point to it.
You should see a readable heading and its related content. The heading level tells readers how the ideas fit together, not merely how large the letters look.
What Should You See?
The page should display “Script Loading” as a heading, followed by its related content. Change the heading text and refresh the browser to see the result.
Open the page and compare what appears in the browser tab with the heading inside the document. Both have different jobs.
Try It Yourself
- Create scripts/site.js and write code that responds to the button click.
- Save your changes, open or refresh the page, and compare the result with the original example.
- Tell a friend what your change did. If you are not sure, undo it, refresh the page, and compare.
Common Beginner Mistakes
- Adding defer to an inline script expecting it to behave like an external deferred script.
- The title in the browser tab and the heading visible in the page are different pieces of information.
Key Takeaways
- The script element brings JavaScript into a document.
- A script adds JavaScript or declares another kind of script data. HTML alone does not run most interactive behavior.
- Defer normally preserves order for classic external scripts and waits until parsing ends. Async executes when ready, which can change ordering.