Rails, Webpacker and Turbolinks - Javascript not loading until leaving the page, or full reload

Viewed 200

I have a javascript file that looks like this:

// javascript/packs/org_chart.js
require("orgchart") // from jquery-orgchart plugin
document.addEventListener("turbolinks:load", () => {
  console.log('org chart loaded')
  $('#org_chart').orgchart({
    ... 
  });
})

and an org_chart.html.erb page that looks like this:

<div id="org_chart"></div>

<%= javascript_pack_tag 'org_chart', 'data-turbolinks-track': 'reload' %>

When I navigate to the org_chart route I expect the script to run but I get a blank page and blank console. I can see that the script was included but it does not run.

Inspect Element showing the script tag

Image showing javascript was loaded

When I navigate away from the page the script appears to run, but because the element is no longer on the page, I get an error. I continue to get this same error in the console every time I navigate until I refresh the page.

Console with error after navigating away

If I navigate back the script runs and the org chart loads correctly. The org chart also loads correctly if I do a refresh after navigating to the page.

When I navigate back and forth between any page and the org_chart page, the script runs again and the org chart duplicates itself each time.

How can I:

  1. Get the script to run when I navigate to the org_chart page.
  2. Get the script to not run when I leave the org_chart page (I thought that was what the javascript_pack_tag was supposed to do)
  3. Stop duplication from happening each time I visit the page.
1 Answers

I am facing silimar situation. I have just disabled turbolink

li{ 'data-turbolinks': 'false' }

But not sure if this is an appropriate solution.

Related