locomotivemtl / astro-boilerplate

Astro project boilerplate by Locomotive
https://locomotive-astro-boilerplate.vercel.app/
MIT License
7 stars 4 forks source link

Scripts and swup bug #14

Closed lucasvallenet closed 1 month ago

lucasvallenet commented 2 months ago

Inline <script> within page templates only trigger once (on first load) and don't trigger afterward.

It's probably related with the swup transition.

Steps de reproduce : Add console.log to home and about page, and navigate back and forth between both pages. The logs will only be triggered once.

arnvvd commented 2 months ago

I think I understand the issue you’re having and why you can’t use the tag in the Astro component that serves as a page. Here’s an explanatory outline:

  1. If you use the script tag in the index.astro component, the log will only fire once during your navigation, when you navigate to the homepage.
    
    ---
    import Layout from '../layouts/Layout.astro';
    ---
    <Layout title="Welcome to the Locomotive Astro Boilerplate.">
    </Layout>

2. If you want to reload an inline script with Swup, you need to use the `data-swup-reload-script` attribute. However, here you will see that if the first page loaded is the homepage, the log will fire on every new page load. And if the first page is the about page, you will never see the log even when loading the homepage.
```.astro
---
import Layout from '../layouts/Layout.astro';
---
<Layout title="Welcome to the Locomotive Astro Boilerplate.">
</Layout>

<script data-swup-reload-script>
    console.log('Hello from the Index page');
</script>
  1. The reason is actually because your script tag is outside of the <main> tag which has the id #swup. In fact, you are not really in the router. Therefore, you need to declare your script within the <Layout/> tag.
    ---
    import Layout from '../layouts/Layout.astro';
    ---
    <Layout title="Welcome to the Locomotive Astro Boilerplate.">
    <script data-swup-reload-script>
        console.log('Hello from the Index page');
    </script>
    </Layout>

Conclusion

You can use <script> tags as you normally would in Astro components while using Swup, without having to use web components (which benefit from the native lifecycle). You need to ensure that they are properly declared in the <Layout/> tag of a page component: either inline within this page component or in a child component. Also, don't forget to add the data-swup-reload-script attribute.