Day9 - Astro Series: Client Side Script

A beautiful gradient background with the title “Scripts”

Introduction

So far, we haven’t covered how to run client-side JavaScript in components. This chapter introduces two approaches: local scripts and external scripts. DOM manipulation typically belongs in client-side scripts, including event listeners, animations, Ajax, and anything else that interacts with the browser.

Using Scripts in Astro

You can include JavaScript in a component by adding a <script> tag to its template. By default, Astro processes <script> tags in component templates as described below, then injects them into <head> with type="module" added.

  • Any import statements are bundled, including imports of local files or Node packages
  • TypeScript is supported
  • Even if a component is used multiple times on the same page, its script is included only once
---
---
<script>
console.log('Welcome, browser console!');
</script>

If you don’t want Astro to manage a component’s script, you can use the is:inline directive to insert it directly into the HTML. Keep in mind, however, that this directive causes the script to run again for every instance of the component.

<script is:inline>
// Written directly into the HTML. Package imports will not work, and this snippet will run again for every instance of the component.
</script>

Including Local Scripts

If your script is located in src/, you can reference the file directly, and Astro will bundle it as well.

<!-- Script path: `src/scripts/local.js` -->
<script src="../scripts/local.js"></script>
<!-- TypeScript is also supported -->
<script src="./script-with-types.ts"></script>

Including External Scripts

If your script is located in public or hosted on a CDN, you can also use is:inline to add it to the page without processing.

<!-- Script path: `public/my-script.js` -->
<script is:inline src="/my-script.js"></script>
<!-- Script URL on a remote server -->
<script is:inline src="https://my-analytics.com/script.js"></script>

Summary

When you want Astro to process scripts, you can add <script> tags directly to your component template. When you need to insert an inline script directly, use the is:inline🔗 template directive. Try adding some functionality to your pages with client-side scripts! For example:

These all make great small practice projects.

Further Reading