How to add JavaScript to a page
Load an external script
For most classic scripts, defer downloads in parallel and runs after HTML has been parsed.
<script src="/js/site.js" defer></script>
Use modules for modern code
Modules are deferred automatically and support import and export.
<script type="module" src="/js/app.js"></script>
Connect behavior accessibly
Begin with working HTML, then enhance it. Listen on a real button rather than a clickable div.
const button = document.querySelector("#preview");
button.addEventListener("click", () => {
document.querySelector("#result").hidden = false;
});
Keep scripts dependable
- Place behavior in external files instead of inline event attributes
- Do not use
document.write() - Handle missing elements and network failures
- Preserve keyboard operation, focus, and status announcements
- Use a Content Security Policy in production where practical