Astro Scripts

Published on December 18th, 2024

As I have been developing this site, I have been learning about how Astro compiles and renders my code. One thing in particular that has stood out to me is how Astro handles the script tag.

Much of this content is taken from Astro's Docs.

Processing

Astro works by compiling a lot of different components and pages together to create a site. A common way to include scripts on these components is by using inline script tags.

By default, Astro will process every script tag. It automatically does the following on scripts:

  • Removes whitespace
  • Shortens variable names
  • It adds type="module" to the script. Amongst other things, this allows for scoped variables which will help avoid any conflicts
  • It only injects the script one time if the component is used multiple times on the page

Astro's script processing ensures that your code is optimized for performance by minimizing file sizes and preventing conflicts in the global namespace. This is particularly beneficial for large-scale applications with numerous components.

Options

is:inline

If you use <script is:inline>, it will remove that script from Astro processing and it will be rendered exactly as written. This can be helpful when dealing with 3rd party code or libraries. For instance, if you're embedding a third-party analytics snippet or a custom script that requires precise formatting, using this ensures the script is injected exactly as written without modification.

define:vars

Using <script define:vars> will allow you to access your frontmatter variables inside your script. The drawback to this if you pass your variables this way, Astro won't process your script, it will be treated as an is:inline script.

Lazy Load JS

There is no built-in way to lazy load Javascript in Astro. Instead, it offers hydration directives like client:visible to control when a component and its associated JavaScript are loaded and executed. Using this directive lazy loads a componenent only when the componenent becomes visible in the viewport. This component has to be using a framework that supports hydration like React or Svelte.

In order to lazy load the component you should put client:visible in the inclusion of the component.

Example
<ComponentName client:visible />

If you click the button it will load and reveal a sample component that uses React to leave a console log and to render a div.

Click here to see the component

Loaded with client:visible!

Conclusion

I have been enjoying the flexibility of using Astro to develop this site. The way it handles scripts is a great example of how it can be customized to fit the needs of the developer. For example, I just included a script and style tag right next to where I wrote the paragraph that explains it. When I build the site, Astro will process the code and inject it at the exact right place in the DOM. It's a very satisfying process.