Let’s take one interactive feature apart so the markup and behavior make sense separately.
What You Need to Know
A normal script may delay parsing while it runs; defer waits until HTML parsing finishes and preserves order for classic scripts; async can run whenever its download finishes. Choose based on whether the script depends on page elements.
In this example: compare scripts that load before and after parsing.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<script src="scripts/site.js" defer></script>
<script src="scripts/analytics.js" async></script>
<main><h1>Learning JavaScript loading</h1></main>
Let’s Read the Code
- <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
- <main>: The main element marks the primary page content.
- src: Src identifies a resource path for images, frames, or media.
Read the named elements and attributes together. They explain how the browser connects this feature to the rest of the page.
What Happens in the Browser?
When this example includes JavaScript, it supplies behavior that ordinary HTML does not automatically provide. Always think about a fallback.
Start with native behavior. Details, dialog, and popover each solve a different interface problem. Choose the simplest control that actually matches what a visitor wants to do, then test focus and dismissal as well as appearance.
Your Turn
Run this on a local development server if it loads modules or resources. Change the visible text or trigger and check what still works with scripts disabled.
Common Beginner Mistakes
- Expecting the page to run scripted behavior when the required JavaScript is missing.
- HTML supplies structure; JavaScript is necessary for the scripted behavior in this example. Check keyboard access and focus movement too.
Key Takeaways
- A normal script may delay parsing while it runs; defer waits until HTML parsing finishes and preserves order for classic scripts; async can run whenever its download finishes.
- <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
- Test the behavior you expect rather than trusting how the snippet looks in your editor.