Chuyển đến nội dung

Bài 11 · Components and Islands

Client-Side Scripts in Astro

Add browser JavaScript to Astro pages with script tags, learn how Astro bundles and deduplicates them, pass data with define:vars and use custom elements.

The code in an .astro frontmatter fence runs on the server, so it cannot react to a click. Interactivity needs JavaScript that runs in the visitor's browser. The simplest way to add it, with no UI framework at all, is a plain <script> tag in your component. This is often all a content site needs: a menu toggle, a copy button, a theme switcher.

Script tags are processed

A <script> in an Astro template is not copied literally. By default Astro processes it:

  • It is bundled with Vite, so you can import from npm packages and from your own files.
  • TypeScript is supported without any configuration.
  • It is output as a module (type="module"), so it is deferred and runs after the HTML is parsed.
  • If the same component appears many times on a page, its script is included once.
ASTRO
---
// src/components/ThemeToggle.astro
---
<button id="theme-toggle" type="button">Toggle theme</button>

<script>
  const button = document.getElementById("theme-toggle");
  button?.addEventListener("click", () => {
    document.documentElement.classList.toggle("dark");
  });
</script>

Because the script runs once for the whole page, selecting by an id only finds one element. If the component might appear several times, select by class or use a custom element (below).

Opting out of processing

Adding any attribute other than src to the tag, or using is:inline, tells Astro to leave it alone. The script is written into the HTML exactly as you typed it, with no bundling, no TypeScript and no deduplication:

ASTRO
<script is:inline>
  // Runs immediately, in place. Useful for tiny snippets such as
  // setting a theme class before the page paints, to avoid a flash.
  const saved = localStorage.getItem("theme");
  if (saved === "dark") document.documentElement.classList.add("dark");
</script>

Use is:inline sparingly: the code is repeated in every page that includes it.

Passing server data to a script

The fence runs on the server and the script in the browser. They do not share variables. To pass values across, use define:vars on an inline script. Astro serializes the values into the script as constants:

ASTRO
---
const greeting = "Hello from the server";
const limits = { max: 5 };
---
<script define:vars={{ greeting, limits }}>
  console.log(greeting, limits.max);
</script>

define:vars implies is:inline, so the script is not bundled and cannot use imports. For bundled scripts, put the data into data-* attributes and read them from the DOM:

ASTRO
---
const { postId } = Astro.props;
---
<button class="like" data-post-id={postId}>Like</button>

<script>
  document.querySelectorAll<HTMLButtonElement>(".like").forEach((button) => {
    button.addEventListener("click", () => {
      console.log("liked", button.dataset.postId);
    });
  });
</script>

Custom elements for reusable behaviour

The most robust pattern for component-level behaviour is a web component. Each instance of the element gets its own connectedCallback, so several copies on one page do not interfere:

ASTRO
---
// src/components/Counter.astro
---
<click-counter>
  <button type="button">Clicked <span data-count>0</span> times</button>
</click-counter>

<script>
  class ClickCounter extends HTMLElement {
    count = 0;
    connectedCallback() {
      const label = this.querySelector("[data-count]")!;
      this.querySelector("button")!.addEventListener("click", () => {
        this.count++;
        label.textContent = String(this.count);
      });
    }
  }
  customElements.define("click-counter", ClickCounter);
</script>

Even if you place <Counter /> five times, the script is bundled once and the browser creates five independent elements.

Choosing a script style

Plain script Bundled once, can import
is:inline Copied as typed
1 / 2

Stand-in: script deduplication

The page builder collects scripts from every component it renders and emits each unique one once. This stand-in shows why five counters do not mean five copies of the code.

Node.js Stand-in: collect and dedupe scripts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: a counter as an event-driven object

In the browser, the counter relies on DOM events. We can model the logic without a DOM, using Node's EventTarget, to confirm that each instance holds its own state.

Node.js Stand-in: independent element instances

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When to reach for an island instead

Plain scripts are great for small enhancements. When a component needs reactive state, a template of its own and frequent updates, a UI framework island is easier to maintain. The next lessons introduce islands and how to control when they load.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does Astro do with a plain <script> in a component?

    Plain scripts are processed by Vite, support imports and TypeScript, and are deduplicated.
  2. 2. How does the script receive a value computed in the frontmatter fence?

    Server and browser code do not share scope. Use define:vars (inline) or data attributes.
  3. 3. What does is:inline change?

    is:inline skips bundling, TypeScript and deduplication.
  4. 4. Why are custom elements good for reusable behaviour?

    connectedCallback runs per element, so many copies of a component do not collide.

Summary

  • A <script> in a component runs in the browser, is bundled as a module and appears once per page.
  • is:inline and define:vars keep the script as typed; define:vars serializes server values into it.
  • For bundled scripts, pass data with data-* attributes.
  • Custom elements give each component instance its own behaviour and state.
  • Use plain scripts for light enhancements and islands for rich interactive UI.

Next: Islands Architecture

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.