As with many of us, I’m trying to integrate Stimulus into an existing Rails app with lots of messy one-off script tags that perform simple functions. (I know, I know.) Ideally, I’d like to refactor all of these, but, in the meantime, they do the job. But, now with Stimulus … maybe not?
I have a particularly complicated page with many forms, each with a Stimulus controller. Inside some of the forms, I call partials to render fields, some of which have
<script> sections to perform JS specific to that partial.
I haven’t been able to troubleshoot completely through this, but it seems that the script tags are interfering with my Stimulus controller. On initialize() or connect(), it’s looking for a few targets later in the page, and it doesn’t find them if there are
<script> tags that are rendered higher in the page than those targets. If I remove the
<script>s, Stimulus acts as expected. Or if I move them to after the Stimulus controller (or maybe even outside the scope of each controller), it also works.
Obviously, there could be specific code inside my
<script> that is causing problems, but I tried just inserting empty
<script></script>, and it also seems to interfere.
So, question: Does Stimulus not play well with
<script> tags? Or might there be something else going on here?