πŸ”₯ All-Access Pass β€” $199 USD (Regular $499) Β· Unlock all 2,836 Astro themes βž”
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Components & Islandsβ€’β€’By Komal Nakrani

Astro View Transitions: Re-Run Scripts After Navigation

Fix scripts that break with Astro view transitions: run setup on astro:page-load, use data-astro-rerun for inline scripts and avoid double-binding listeners.

#Astro#View Transitions#ClientRouter#JavaScript

With Astro view transitions (<ClientRouter />), bundled scripts run only once, on the first page load, so code that queries the DOM stops working after you navigate. The fix is to wrap the setup in a function and call it on the astro:page-load event, which fires on the first load and after every navigation. For is:inline scripts that must execute on every page, add the data-astro-rerun attribute.

Key Takeaways

  • Bundled <script> modules execute once per session with the client router, not once per page.
  • document.addEventListener('astro:page-load', setup) runs your setup after every navigation.
  • data-astro-rerun makes an inline script run again each time it appears.
  • Listeners on document or window persist; add them once, outside the page-load handler.

Why scripts stop working

Without the router, every navigation is a full page load and every script runs again. With <ClientRouter />, Astro fetches the next page, swaps the DOM, and keeps the JavaScript running. Module scripts that already executed are not executed again, by design, so the elements your script attached listeners to are gone, and the new ones never get them.

<!-- Before: works on first load, breaks after navigating -->
<script>
  document.querySelector('.menu-toggle')?.addEventListener('click', () => {
    document.body.classList.toggle('menu-open');
  });
</script>

The fix: astro:page-load

---
// src/components/MenuToggle.astro
---
<button class="menu-toggle" type="button" aria-expanded="false">Menu</button>

<script>
  function setupMenu() {
    const button = document.querySelector<HTMLButtonElement>('.menu-toggle');
    if (!button) return;
    button.addEventListener('click', () => {
      const open = document.body.classList.toggle('menu-open');
      button.setAttribute('aria-expanded', String(open));
    });
  }

  document.addEventListener('astro:page-load', setupMenu);
</script>

astro:page-load fires after the first page load and after each navigation completes, once the new DOM is in place. The listener itself is added once, because the script runs once; the setup function runs every time.

This also works without the router: the event still fires on the initial load, so the same component works whether a site enables view transitions or not.

Inline scripts: data-astro-rerun

Scripts with is:inline are not bundled. With the router, an inline script that already ran is skipped on later pages unless you mark it:

<script is:inline data-astro-rerun>
  document.documentElement.dataset.page = location.pathname;
</script>

Use this for small snippets that must run on every page, such as third-party embeds that scan the DOM once.

Avoid binding twice

Listeners on elements that are replaced during navigation are cleaned up with those elements. Listeners on document or window are not; they survive every swap. Add those once, at the top level of the script, not inside the page-load handler:

// Good: added once
window.addEventListener('resize', onResize);
document.addEventListener('astro:page-load', setupPage);

// Bad: adds another resize listener on every navigation
// document.addEventListener('astro:page-load', () => window.addEventListener('resize', onResize));

If something must be torn down before leaving a page (an interval, an observer), do it on astro:before-swap:

let timer: number | undefined;
document.addEventListener('astro:page-load', () => {
  timer = window.setInterval(updateClock, 1000);
});
document.addEventListener('astro:before-swap', () => clearInterval(timer));

Other lifecycle events

Event When it fires Typical use
astro:before-preparation Before the next page is fetched Show a loading indicator
astro:after-preparation After the next page is loaded Hide the indicator
astro:before-swap Just before the DOM is replaced Clean up, adjust the new document
astro:after-swap Right after the DOM is replaced Re-apply a theme class before paint
astro:page-load After the page is ready Set up components

Dark mode toggles usually use astro:after-swap to re-apply the theme class before the new page paints, which avoids a flash; our dark mode toggle guide shows it.

Framework islands are different

React, Svelte and Vue islands on the new page hydrate on their own, so they don’t need any of this. The events matter for plain scripts. If you want an island to survive navigation instead of remounting, use transition:persist.

The view transitions guide covers the router in depth, and ClientRouter vs native view transitions explains when you need the router at all. The config docs show where it’s enabled in a Komal theme; our Astro themes write their scripts this way so they work either way.

FAQ

Why do my scripts stop working after navigation in Astro?

With <ClientRouter />, bundled scripts run only on the first page load. Wrap the DOM setup in a function and call it on the astro:page-load event.

What does data-astro-rerun do?

It tells the client router to execute an is:inline script again every time a page containing it is loaded, instead of skipping it after the first run.

Does astro:page-load fire on the first page load?

Yes. It fires on the initial load and after every view transition navigation, so one listener covers both.