Small interactions can make a webpage easier to use: opening a tip, changing a setting, or reusing an interface component.
What You Need to Know
Module scripts support import and export, have their own scope, and are deferred by default. They work best when served from a development server rather than opened as local file URLs.
In this example: import a helper from a local module.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<script type="module">
import { greet } from "./scripts/helpers.js";
greet("Alex");
</script>
<p>Serve module files through a local development server.</p>
Let’s Read the Code
- <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
- type: Type changes what sort of control or resource the browser uses.
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.
What makes it interactive? Look for the JavaScript that finds an element and reacts to an event. HTML provides the initial controls and content; the script updates the page. Try removing the script to see which part still works natively.
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
- Module scripts support import and export, have their own scope, and are deferred by default.
- <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.