简体   繁体   English

Rails、Webpacker 和 Turbolinks - Javascript 在离开页面或完全重新加载之前不加载

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

I have a javascript file that looks like this:我有一个看起来像这样的 javascript 文件:

// 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:和一个看起来像这样的org_chart.html.erb页面:

<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.当我导航到org_chart路由时,我希望脚本能够运行,但我得到一个空白页面和空白控制台。 I can see that the script was included but it does not run.我可以看到该脚本已包含在内,但它没有运行。

检查显示脚本标签的元素

显示 javascript 的图像已加载

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.每次导航时,我都会在控制台中继续收到相同的错误,直到刷新页面。

导航离开后出现错误的控制台

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.当我在任何页面和 org_chart 页面之间来回导航时,脚本会再次运行,并且组织结构图每次都会自我复制。

How can I:我怎样才能:

  1. Get the script to run when I navigate to the org_chart page.当我导航到 org_chart 页面时,让脚本运行。
  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)当我离开 org_chart 页面时,让脚本不运行(我认为这是javascript_pack_tag应该做的)
  3. Stop duplication from happening each time I visit the page.每次访问该页面时都不会发生重复。

I am facing silimar situation.我面临着类似的情况。 I have just disabled turbolink我刚刚禁用了 turbolink

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

But not sure if this is an appropriate solution.但不确定这是否是一个合适的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM