#JavaScript with ViewTransitions

1 messages · Page 1 of 1 (latest)

sullen valley
#

When I use ViewTransitions, the JavaScript of the page doesn't always get loaded. How do I make sure it gets executed?

grand mauveBOT
#

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

#

When using the <ViewTransitions /> component in Astro, scripts are run in sequential order to match browser behavior. However, they are not automatically re-executed when navigating between pages. This means that if you have code that sets up global state, you need to take into account that the script might execute more than once. You can check for the global state in your <script> tag, and conditionally execute your code where possible:

<script is:inline> if(!window.SomeGlobal) { window.SomeGlobal = {} // .... }</script>

Module scripts, including those that add event listeners for DOMContentLoaded, are only ever executed once because the browser keeps track of which modules are already loaded. To re-execute scripts during client-side page navigation, you must add listeners for a Lifecycle event.

For example, you can add an event listener for the astro:after-swap event to re-initialize your libraries on the transitioned to page:

<script>
  import { aosInit } from "@js/aos";

  // runs on initial page load
  aosInit();

  // runs on view transitions navigation
  document.addEventListener("astro:after-swap", aosInit);
</script>

You can also use the astro:page-load event to re-execute scripts when a new page is loaded.

For more information, you can refer to the Astro documentation on View Transitions (https://docs.astro.build/en/guides/view-transitions/#script-behavior-during-page-navigation) and the Add View Transitions Tutorial (https://docs.astro.build/en/tutorials/add-view-transitions/#update-scripts).

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

#

@sullen valley kapa.ai is still learning and improving, please let us know how it did by reacting below