Components and layouts

Add a browser script

Distinguish a script tag that Astro bundles for the browser from frontmatter that runs only while rendering.

8 minute lesson

~~~

Use a <script> tag when the finished HTML needs behavior in the browser:

<button data-menu-button aria-expanded="false">Menu</button>
<nav data-menu hidden>...</nav>

<script>
  const button = document.querySelector("[data-menu-button]")
  const menu = document.querySelector("[data-menu]")

  button?.addEventListener("click", () => {
    const open = button.getAttribute("aria-expanded") === "true"
    button.setAttribute("aria-expanded", String(!open))
    if (menu instanceof HTMLElement) menu.hidden = open
  })
</script>

Astro processes a normal script: imports can be bundled, TypeScript is supported, and repeated use of the component does not imply repeated copies of the same bundled script. An is:inline script is emitted as written and skips that processing, so use it only when inline behavior is specifically required.

This code is public. Never include secrets, private environment values, or authorization logic in it.

Prefer native HTML before JavaScript. Links should navigate with <a>, forms should submit with <form>, and disclosure behavior may fit <details>. Add a script for behavior HTML cannot provide clearly, then test the page with JavaScript disabled to see whether its essential content still works.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →