i see i can use after-preparation or after-swap to run scripts. but what if i want to run a script as the page is loading? I can use page-load but that's after it's loaded. is there a after-preparation for the first load (e.g. before the viewtransition happens on the next page) but they are already on a page. how could i have ran a script on the original page, before they click on a link to a next page
#viewtran
3 messages · Page 1 of 1 (latest)
Hi @elfin island. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro provides several lifecycle events that you can use to run scripts at different stages of the page loading process. However, if you want to run a script as the page is loading, before any view transitions occur, you can simply include your script in the HTML of your page without tying it to any specific Astro event.
Here's an example:
<script>
// Your script here
</script>
This script will run as soon as the browser encounters it during the page load, which is typically before any view transitions occur.
If you want to run a script specifically when the user clicks on a link to navigate to a new page, you could add an event listener to the links on your page:
<script>
document.querySelectorAll('a').forEach(link => {
link.addEventListener('click', () => {
// Your script here
});
});
</script>
This script will run when the user clicks on any link on the page, before the view transition to the new page begins.
Remember that these scripts will run on every page load, not just the first one. If you want a script to run only once, you could use the astro:page-load event with the { once: true } option, as shown in the Astro documentation (https://docs.astro.build/en/guides/view-transitions#astropage-load):
<script>
document.addEventListener('astro:page-load', () => {
// Your script here
}, { once: true });
</script>