#How to re-run script on each page load

2 messages · Page 1 of 1 (latest)

grand saffronBOT
#

Hi @floral yacht. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To run a script on each page load in Astro, you can use the astro:page-load lifecycle 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. You can listen to this event on the document.

Here is an example of how to use this event:

<script>
  document.addEventListener('astro:page-load', () => {
    // Your code here...
  });
</script>

This script will run every time a page is loaded during client-side navigation. If you want the script to run only once, you can use the { once: true } option:

<script>
  document.addEventListener('astro:page-load', () => {
    // This only runs once.
    // Your code here...
  }, { once: true });
</script>

For more information, you can refer to the Astro documentation on lifecycle events (https://docs.astro.build/en/guides/view-transitions/#astropage-load).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: