Stimulus controller initialize twice by turbolinks when navigation

30 Jul 2020

Recently I found the stimulus controller’s init function will be call twice. After some research, I found this:

… during standard navigation, 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. – turbolinks/turbolinks - Understanding Caching

It’s now a bug, it’s a freature.

So the first controller is initialized by Trubolinks preview flow. The second controller is initialzed by the refreshed codebase.

But, what if I only want some code to only run once in stimulus init function with turbolinks. Below is the solution:

if (!document.docuementElement.hasAttribute("data-turbolinks-preview")) {
  // Code ...
}

References

Back to top