Controller initialized twice when visiting from a Turbolinks page

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

Here is the example Rails app I used to create that gif.

I’m not sure if it’s an issue or not but something unusual I notice while debugging something else.

1 Like

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:

  1. 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.
  2. Log the value of document.documentElement.hasAttribute("data-turbolinks-preview"). You should see true when Turbolinks is showing the preview.

Thanks @sam, that totally makes sense. Everything seems to be working as you described.

Double :+1::+1: for @sam

1 Like

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 !!