When using Turbolinks and I visit a page that has a Stimulus controller the controller’s initialize function is called twice. Here’s a gift showing it happening
I had something similar happen but it was because I was sending an HTML fragment with the data-controller attribute from the server. This was causing it to connect again when that fragment was added to the DOM.
I believe everything is working as expected here. You’re seeing Turbolinks’ preview cache in action:
[D]uring standard navigation (via Application Visits), Turbolinks will immediately restore the page from cache and display it as a preview while simultaneously loading a fresh copy from the network. This gives the illusion of instantaneous page loads for frequently accessed locations.
The first controller is initialized when Turbolinks renders the preview. Then the preview <body> is replaced by fresh page content loaded over HTTP, which initializes a second controller.
Try these two things to confirm:
Log in connect() and disconnect() instead of initialize(). You should see a corresponding call to disconnect() for the first controller before the second controller connects.
Log the value of document.documentElement.hasAttribute("data-turbolinks-preview"). You should see true when Turbolinks is showing the preview.
I’m using The latest Stimulus with Rails 7 …
Now I’m observing this behavior only whenever I do hard refresh to the page … then I try to active an action, it goes twice !!