In Astro components we can write JavaScript in the component frontmatter:
---
const name = 'joe'
---
<p>test</p>
and we can use any JavaScript variable we define inside the markup:
---
const name = 'joe'
---
<p>{name}</p>
This JavaScript is executed at build time.
It’s not running in the browser and it’s not ran every time a user requests the page.
To add JavaScript code that’s executed client-side, you write it in a <script>
tag inside the markup:
---
const name = 'joe'
---
<p>{name}</p>
<script>
alert('test')
</script>
It’s important to note that Astro is processing this code and for example if you include it in a component that’s reused multiple times, the code is only executed once.
Also, any code is executed after the DOM has fully loaded because it’s loaded as a module (and automatically deferred).
You can opt-out of this behavior by adding an inline script:
---
const name = 'joe'
---
<p>{name}</p>
<script is:inline>
alert('test')
</script>
In this case the script is added to the page as-is, and if you try you’ll already see the difference, the alert()
in this case is executed before the DOM is loaded (you don’t see anything in the DevTools inspector):
In this case, if you need, you have to wait for the DOM to fully load yourself, using an event listener:
<script is:inline>
document.addEventListener(
. 'DOMContentLoaded', () => {
alert('test')
})
</script>
You can also include JavaScript files in Astro templates, using relative URLs:
<script src="../script.js"></script>
or absolute URLs if those scripts are in the public
folder:
<script src="/script.js"></script>
Astro bundles those unless you opt out with is:inline
.