Turbo Drive + ECharts: Fixing History Back
You got a Rails app with Turbo Drive and some charts powered by ECharts.
It works fine until you navigate to another page and hit the back button.
When navigating back in the browser history, somehow Turbo can't deal with the charts and displays an empty square instead of rendering them. Only a full page refresh can make them appear again.
The Lazy Solution
The simpler (but not so nice) solution is to disable Turbo Drive for all links on that particular page which contains the charts:
But that would downgrade the user experience, so it's kinda meh.
A Better Solution
Turbo Drive caches the current page before requesting the clicked link, so I thought, what if I dispose the charts before saving the cache?
We can use the
turbo:before-cache callback to remove all chart instances upon navigation:
In the example above two charts are created and stored in the
allChartInstances array when the page first load. Before caching the page they are properly removed and when navigating back they will be re-created on