Adding JavaScript to HTML
There are three ways to add JavaScript to a page: inline, internal, and external — similar to how CSS can be added.
<button onclick="alert('Hi!')">Click me</button>
<script>
console.log("Internal script running");
</script>
<script src="app.js" defer></script>
External scripts (loaded via src) are the standard for real projects — they're cacheable by the browser, reusable across multiple pages, and keep your HTML markup clean and readable.
The defer attribute tells the browser to download the script in parallel while it keeps parsing the HTML, but to only run it after the document is fully parsed — this is why defer is the recommended default for <script> tags placed in <head>. The async attribute downloads in parallel too, but runs the script the moment it's ready, which can happen before parsing finishes and out of order relative to other scripts — fine for independent scripts like analytics, risky for scripts that depend on the DOM or on each other.