JS Where To
JavaScript can live in three places: inline in the HTML, in a <script> block, or in an external .js file. Where you put it changes loading order and cacheability.
Three placements
| Where | How | Use when… |
|---|---|---|
| Inline event | <button onclick="alert('hi')"> | Quick demos. Avoid in production — mixes structure and behaviour. |
| Internal <script> | Block inside HTML | Page-specific glue, critical-above-the-fold script. |
| External file | <script src="app.js"> | Reusable code, cacheable across pages — the standard for production. |
defer vs async
| Attribute | Behaviour |
|---|---|
| (none) | Browser stops parsing HTML, downloads, runs the script, then resumes parsing. Blocks rendering. |
defer | Downloads in parallel with parsing. Runs after HTML is parsed, in source order. |
async | Downloads in parallel. Runs as soon as it's ready — order is not guaranteed. |
type="module" | Implicitly deferred. Treats the file as an ES module (supports import). |
Modern recommended setup
HTML
<head> <script src="app.js" defer></script> </head>
Tip:
defer is the safe default for most app code. Use async only for analytics or other independent scripts.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Where To!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Load app.js in <head> without blocking page rendering.
<script src="app.js"
></script>
Five letters. Runs after HTML is parsed.
Discussion
Loading…