docs icon indicating copy to clipboard operation
docs copied to clipboard

View Transitions Script Behavior

Open OliverSpeir opened this issue 1 year ago • 2 comments

📋 Explain your issue

The /view-transitions/#script-re-execution section I think is not correctly directing users to the truly happy path. Ideally for most users a lifecycle event would be listened for in order to deal with script rexecution. data-astro-rerun should only be used when necessary, after considering using a lifecycle event.

Commonly users might reach for data-astro-rerun when in fact they want to only run a callback on certain pages. This section could help users stay on the happy path by giving an example of checking if an element is on the page before running a function related to it like this example.

OliverSpeir avatar Apr 24 '24 02:04 OliverSpeir

We always want to keep our users on a happy path!

Is anyone interested in taking a closer look at docs and suggesting some improvements?

sarah11918 avatar May 04 '24 22:05 sarah11918

Just pinging this for freshness in case anyone is interested in taking this on!

sarah11918 avatar Jun 15 '24 15:06 sarah11918

Still open to someone adding a paragraph in the script reexecution section with an example, something maybe like (mostly taken from the View transitions tutorial):

### Script re-execution

[Bundled module scripts](https://docs.astro.build/en/guides/client-side-scripts/#script-processing), which are the default scripts in Astro, are only ever executed once. After initial execution they will be ignored, even if the script exists on the new page after a transition.

Unlike bundled module scripts, [inline scripts](https://docs.astro.build/en/guides/client-side-scripts/#opting-out-of-processing) have the potential to be re-executed during a user’s visit to a site if they exist on a page that is visited multiple times. Inline scripts might also re-execute when a visitor navigates to a page without the script, and then back to one with the script.

With view transitions, some scripts may no longer re-run after page navigation like they do with full-page browser refreshes. There are several [events during client-side routing that you can listen for]#lifecycle-events), and fire events when they occur. You can wrap an existing script in an event listener to ensure it runs at the proper time in the navigation cycle.

```js title="src/scripts/menu.js" ins={1,5}
document.addEventListener('astro:page-load', () => {
  document.querySelector('.hamburger').addEventListener('click', () => {
    document.querySelector('.nav-links').classList.toggle('expanded');
  });
});
```

#### data astro rerun

Would something like this prompt people to try lifecycle events first?

sarah11918 avatar Sep 24 '24 16:09 sarah11918