Controller initialized twice when visiting from a Turbolinks page


#1

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

screen

Here is the example Rails app I used to create that gif. https://github.com/scottharvey/stimulus_asset_pipeline

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


#2

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.


#3

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.

#4

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