Javascript in or for snippets: thoughts / best practices?

Hi there.

I read that the bottom code takes the equivalent javascript for templates. Which is awesome.

<?= js([
  '@auto'
]) ?>

Yet I wonder is there a similar way for snippets?

I hoped it (the @auto) would work something like assets/js/snippets/my-snippet.js as my snippet is stored as site/snippets/my-snippet.php

On a side note => how do you manage this?

I have many snippets that have a script tag. These are snippets I use on every site, so I keep the javascript in one file.

For example:

my-snippet.php

 <div class="snippet">
  <p>Some reusable stuff</p>
</div>
<script>
 Some javascript specific for that snippet
</script>

When I use these snippets, the JavaScript is mixed with the HTML in the source code of my pages. Specifically, if you look at the HTML source or body, you’ll see the JavaScript right below where the snippet is used.

I keep my snippets this way because it ensures I never lose any code.
Ofcouse I could cut out the code and move it to my index.js during production. but it all seems to cumbersome… or I am overthinking it.

While this isn’t necessarily bad for SEO, it could potentially interfere with crawlers or delay the page load, which might be an issue.

On the other hand, loading the necessary JavaScript in the footer would mean it gets loaded even when the snippet itself isn’t used, which doesn’t seem ideal to me either.

I’m curious how you handle this or what the best practice would be?
Thank you!