iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

WhereHowUse when…
Inline event<button onclick="alert('hi')">Quick demos. Avoid in production — mixes structure and behaviour.
Internal <script>Block inside HTMLPage-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

AttributeBehaviour
(none)Browser stops parsing HTML, downloads, runs the script, then resumes parsing. Blocks rendering.
deferDownloads in parallel with parsing. Runs after HTML is parsed, in source order.
asyncDownloads 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>

Test yourself

Q1. Which loads in parallel and runs after HTML parsing?
Q2. Which loads in parallel and runs as soon as ready (order not guaranteed)?
Q3. Modules with `type="module"` are…

Discussion

Loading…