stimulus-content-loader icon indicating copy to clipboard operation
stimulus-content-loader copied to clipboard

When using with turbolinks fetch is fired twice when visiting a cached page

Open blafri opened this issue 4 years ago • 0 comments

Hey I think I found an issue with this component when using with turbo links. When I originally browse to the page where I am using the content-loader controller it works fine and fires off a fetch to load the content. The problem occurs when I browse away from the page, and then back again, the fetch is fired twice. This seems to be because of turbolinks caching.

When I browse back to the page after turbolinks stored the page in the cache, turbolinks will immediately restore the page from cache, which will cause the controllers connect to fire and a fetch will be issued. Then turbo links does an XHR request to get the current page from the server, and when that page is returned the cache page will be replaced with the new page that also contains the controller, and therefore another fetch will be fired. In the screen shot below you can see the initial request which works great.

image

The screen shot below shows what happens when visiting the page after the page has been cached by turbolinks.

image

Turbolinks adds a data-turbolinks-preview attribute to the document when it is showing a preview so I think this can be fixed easily by placing the following code in the connect method

if (document.documentElement.hasAttribute("data-turbolinks-preview")) {
  return;
}

I am pretty new to programming so I might be totally missing something and not using the controller properly, or there may be a better way to solve this problem. Let me know what you think.

blafri avatar Feb 17 '21 16:02 blafri