withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.93k stars 2.49k forks source link

Problem with "astro:page-load" and script re-execution. #12494

Open dav-leda opened 18 hours ago

dav-leda commented 18 hours ago

Astro Info

Astro                    v4.16.14
Node                     v18.17.1
System                   macOS (arm64)
Package Manager          pnpm
Output                   static
Adapter                  none
Integrations             @astrojs/tailwind
                         @astrojs/mdx
                         @astrojs/sitemap
                         astro-icon
                         astro-icon

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

I'm using View Transitions, wrapping event listeners inside an 'astro:page-load' event for script re-execution like so:

document.addEventListener('astro:page-load', () => {
  document.querySelector('#some-button').addEventListener('click', () => {
    alert('Button clicked')
  });
});

When navigating out of the page where the event listener is, I get the following error in the browser's console:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at HTMLDocument.<anonymous> (about.astro:19:11)
at triggerEvent (router.js?v=eff4607c:17:41)
at onPageLoad (router.js?v=eff4607c:18:26)
at router.js?v=eff4607c:334:5

It seems that the script is added to every page so that it gets re-executed on every navigation, but if the event listener is attached to an element that exists on just one page the element won't be found on the next page and an error will be thrown.

The example shown in the docs is for a Nav component that's present on every page, but that's not always the case.

This error message can be avoided with optional chaining (document.querySelector('#some-button')?.addEventListener... etc) however, I think this is something you might want to warn about in the docs, or refactor router.js to address this issue.

What's the expected result?

No error messages in the browser's console.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-4hf8r3?file=src%2Fpages%2Fabout.astro

Participation