#Client script view transitions
7 messages · Page 1 of 1 (latest)
Hi @wide jungle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro provides lifecycle events that you can use to control when your scripts run during view transitions. To execute a script before a page loads for the first time, you can use the astro:before-preparation event. This event fires at the beginning of the preparation phase, after navigation has started but before content is loaded.
Here is an example of how you can use this event:
<script is:inline>
document.addEventListener('astro:before-preparation', ev => {
const originalLoader = ev.loader;
ev.loader = async function() {
const { startSpinner } = await import('./spinner.js');
const stop = startSpinner();
await originalLoader();
stop();
};
});
</script>
In this example, a loading spinner is shown before the content is loaded and stopped immediately after loading. You can replace the spinner logic with your own script.
Remember that this event is fired before the content is loaded, so if your script depends on the DOM, you might want to use another event like astro:after-preparation or astro:page-load which fire after the new page’s content has been loaded and parsed into a document.
For more information, you can refer to the Astro documentation on view transitions (https://docs.astro.build/en/guides/view-transitions/#astrobefore-preparation).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@agile inlet kapa.ai is still learning and improving, please let us know how it did by reacting below
@undone sluice this works but only fires in the navigations after the first time the page is loaded. I want both. both the first time you anter a webpage and then the navigation in it
Let me check the knowledge base for you. One moment! :books:
To run a script both on the initial page load and on subsequent navigations, you can use the astro:page-load event. This event fires at the end of page navigation, after the new page is visible to the user and blocking styles and scripts are loaded.
Here is an example of how you can use this event:
<script>
document.addEventListener('astro:page-load', () => {
// Your code here
});
</script>
In this example, the code inside the event listener will run on every page navigation, including the initial page load.
If you want the script to run only once ever, you can add { once: true } as an option to the event listener:
<script>
document.addEventListener('astro:page-load', () => {
// This only runs once.
}, { once: true });
</script>