Turbo Drive + ECharts: Fixing History Back

Problem

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:

<head>
  ...
  <meta name="turbo-visit-control" content="reload">
</head>

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?

That worked.

We can use the turbo:before-cache callback to remove all chart instances upon navigation:

let allChartIntances = []

document.addEventListener('turbo:before-cache', function() {
  allChartIntances.forEach(chartInstance => chartInstance.dispose())
})

document.addEventListener('turbo:load', function() {
  let fooChart = echarts.init(fooContainer);
  allChartIntances.push(fooChart)

  let barChart = echarts.init(barContainer);
  allChartIntances.push(barChart)
})

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 turbo:load.

Written on April 3, 2023

Share: