JavaScript ยท Chapter 2 of 55

Where To Place JavaScript

JavaScript code can live in three places: inline in an HTML attribute, inside a `<script>` tag in the HTML document, or in an external `.js` file linked with `<script src="...">`.

External files are the best practice for real projects because they separate structure (HTML) from behaviour (JS), and browsers can cache them.

Syntax
<script src="app.js"></script>

Internal scripts

You can place a `<script>` block anywhere in the `<head>` or `<body>`. Placing scripts at the end of `<body>` lets the page render before JS runs.

External scripts

Use `<script src="app.js"></script>` to load code from a separate file. This enables browser caching and keeps HTML clean.

Example 1 (html)
<script>
  console.log("Inline script running");
</script>
Output
Inline script running

A script tag embedded directly in HTML.

Example 2 (html)
<script src="app.js" defer></script>

The defer attribute delays execution until HTML parsing finishes.

Key points

  • Scripts can be inline, internal, or external.
  • External files promote reuse and caching.
  • Place scripts before `</body>` or use `defer` for performance.
  • The `src` attribute points to an external JS file.
๐Ÿ’ก Note: Using `defer` or `async` on script tags avoids blocking page rendering.

๐Ÿ“ Quick Quiz

1. Which attribute loads an external JS file?

2. Why put scripts before </body>?

3. What does the `defer` attribute do?