#ViewTransisions with external scripts src

3 messages · Page 1 of 1 (latest)

dusky basalt
#

How would you make this script load properly with view transisions.

<script async src="https://cdn.snipcart.com/themes/v3.3.3/default/snipcart.js">
</script>
agile mulchBOT
#

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

#

Based on the information from the provided extracts, it seems that scripts are not automatically re-executed during view transitions in Astro. This means that if you navigate to a new page, the script won't reinitialize.

However, there are a few potential solutions to this issue:

  1. You can add an event listener for the astro:after-swap event, which is called after every transition. This can be used to reinitialize the script once the new page is loaded. Here's an example of how you might do this:
<script>
  function loadScript() {
    var script = document.createElement('script');
    script.src = '<https://cdn.snipcart.com/themes/v3.3.3/default/snipcart.js';>
    script.async = true;
    document.head.appendChild(script);
  }
  document.addEventListener('astro:after-swap', loadScript);
  loadScript();
</script>
  1. Another approach discussed in the extracts is to use the transition:persist attribute on a component that includes the script. This attribute keeps the component active during navigation events, which might help with scripts that need to maintain their state across page transitions.

Remember to test these solutions thoroughly, as the behavior can depend on the specifics of the third-party script you're using.

Sources:


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