script element
Use script to run JavaScript in an HTML document. Choose loading attributes based on whether execution order and document readiness matter.
What you will learn
- How to load inline and external JavaScript
- How
defer,async, and modules differ - How to avoid blocking the page and reduce security risks
Basic usage
Use src to load an external file, or place a small script between the opening and closing tags. A script with src should not also contain inline code.
External and inline scripts
<script src="app.js" defer></script>
<script>
console.log('A small inline script');
</script>
Choose a loading mode
defer- Downloads while HTML is parsed, then runs after parsing in document order. This is a good default for scripts that use the page's elements.
async- Runs as soon as its download finishes. Use it for independent scripts such as analytics where order does not matter.
type="module"- Loads an ES module with
importandexport. Modules are deferred by default and have their own scope.
A module entry point
<script type="module" src="./main.js"></script>
// main.js
import { add } from './math.js';
console.log(add(2, 3));
Execution and security tips
- Use
deferwhen scripts depend on each other or on parsed HTML. - Use HTTPS and trustworthy sources for third-party scripts; review what they can access.
- Use a Content Security Policy where possible, and avoid inserting untrusted text as executable HTML.
- Keep scripts in external files when they are reused, tested, or maintained by a team.