Inline JS executed after turbo:load

Hey, maybe someone stumbled across the same issue before and can help out:

I initialize graphs with inline JS. I attach the loading to the turbo:load event. However there (seems to be) no guarantee that inline JS is evaluated (i.e. the handler attached), before the turbo:load event fires. I tried to avoid the handler and execute directly, however this gets me into trouble as well, due to the rails caching mechanisms there are situations where charts are initialized twice. I tried to store state in the data-attributes, but there are race conditions as well.

Does anyone have a smart solution?

Using
gem “rails”, “~> 8.0.0”
gem “turbo-rails”, “= 2.0.11”

You could try doing it inside of a Stimulus controller in the connect() method initializing the charts and then in the disconnect() method removing the charts. If the library has a destroy() method you could call u can do that there.

This way StimulusJS handles the initializing and teardown of your JS code