From 9235649ce2fa993a6361c625f634661592054e87 Mon Sep 17 00:00:00 2001 From: Oliver Speir <115520730+OliverSpeir@users.noreply.github.com> Date: Sat, 9 Mar 2024 12:12:36 -0700 Subject: [PATCH] update script behavior section (#6798) Co-authored-by: Martin Trapp <94928215+martrapp@users.noreply.github.com> Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: Sarah Rainsberger --- .../docs/en/guides/view-transitions.mdx | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/content/docs/en/guides/view-transitions.mdx b/src/content/docs/en/guides/view-transitions.mdx index a885ec1ba564a..60ddc7d45b5b3 100644 --- a/src/content/docs/en/guides/view-transitions.mdx +++ b/src/content/docs/en/guides/view-transitions.mdx @@ -453,11 +453,33 @@ When using the `` router, the following steps occur to produc 7. The router executes any new scripts added to the page. 8. The `astro:page-load` event fires. This is the end of the navigation process. -## Script behavior during page navigation +## Script behavior with view transitions + +When you add view transitions to an existing Astro project, some of your scripts may no longer re-run after page navigation like they did with full-page browser refreshes. Use the following information to ensure that your scripts execute as expected. + +### Script order When navigating between pages with the `` component, scripts are run in sequential order to match browser behavior. -If you have code that sets up global state, this state will need to take into account that the script might execute more than once. Check for the global state in your ` +``` + +To ensure that a script runs every time a page is loaded during client-side navigation, it should be executed by a [lifecycle event](#lifecycle-events). For example, event listeners for `DOMContentLoaded` can be replaced by the [`astro:page-load`](/en/guides/view-transitions/#astropage-load) lifecycle event. + +If you have code that sets up a global state in an inline script, this state will need to take into account that the script might execute more than once. Check for the global state in your ` ``` -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. You must add listeners for a [Lifecycle event](#lifecycle-events) to re-execute scripts during client-side page navigation. See the [Add View Transitions Tutorial](/en/tutorials/add-view-transitions/#update-scripts) for an example of updating existing scripts in a project.