CONTEXT
I have a custom scrollbar that I control with JavaScript. This code needs to be executed without too much delay, because otherwise the user will see the elements that make up the scrollbar jump into their positions. The user should, instead, see the elements at their proper positions immediately.
The page I use the scrollbar on is part of a multi-page live session. I use live navigation (both pathing and redirecting) within this live session.
PROBLEM
When I use a mounted hook the JS script loads too late. When I import the script into my app.js (the ESbuild entry point), it is quick enough, but it load on all pages, not just the ones with the scrollbar on it – resulting in errors in the browser since it cannot always find the elements the script is referring to. If I create an extra ESbuild entry point and add a <script defer src=.../> to the LiveView that uses the scrollbar, the js script does load and also fast enough, but it only loads when I directly visit the URL that points to a page/component that includes the scrollbar. When I use live navigation (which a user will often), it does not load.
QUESTION
Any advice on how to include path-dependent JS scripts into a project would be very welcome. It’s not really about making my JS reference work properly, because I know I can find a way to do it. It’s more about finding a way that is pleasant to work with and fault tolerant. For example, solving the problem by including an event listener in my app.js that listens for navigation to specific paths, to then load additional scripts, seems maybe not the best possible option.
Thank you once again.






















