Question regarding memory (w/ Stimulus + Turbolinks)

A controller is stored and re-connected whenever their this.element gets put back in the main DOM tree. For an app that uses Turbolinks, does that mean that controllers are stored in memory for the entire Turbolinks session? And that the list of controllers stored by Stimulus (in memory) will grow over time with controller instances whose this.element will never be reattached?

  • This would mean that there’s a memory leak
  • There’s potential for stale controller instances who are storing references to nodes with a large tree.

Thanks in advance for answering my questions.

Turbolinks stores cloned copies of pages so Stimulus controllers are disconnect()ed and freed from memory:

Turbolinks saves a copy of the current page to its cache just before rendering a new page. Note that Turbolinks copies the page using cloneNode(true), which means any attached event listeners and associated data are discarded.

You can confirm this by logging the number of controllers Stimulus is tracking after each navigation:

const application = Application.start()

// …

addEventListener("turbolinks:load", event => {
  requestAnimationFrame(() => {
    console.log(`Connected controllers: ${application.controllers.length}`)