【问题标题】:Loading position of javascript in rails app在rails应用程序中加载javascript的位置
【发布时间】:2021-05-08 19:10:02
【问题描述】:

我的应用程序中有两部分似乎需要我在不同的位置加载我的 javascript。

  1. 当我将<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' 放在<head></head> 中时,Omniauth 可以工作。
  2. 当我将 <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' 放在 </body> 之前时,Shubox(用于上传照片的 js 库)工作。

当 javascript 在另一个需要的地方加载时,两者都不起作用。因此,如果我将 javascript 行放在正文的末尾,omniauth 不起作用。

如果需要,我可以提供更多信息。提前谢谢你。

application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

application.html.erb

<html>
  <head>
     <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  </head>
    <body data-shubox="<%= Rails.application.credentials.dig(:aws, :secret_access_key) %>">
    <% if flash.any? %>
      <% flash.each do |key, value| -%>
        <section class="flash flash__<%= key %>"><%= value.html_safe %></section>
      <% end -%>
    <% end %>
    <%= yield %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </body>
</html>

【问题讨论】:

  • 就在正文结束之前应该对两者都有效,在这种情况下你是否看到omniauth有一些错误?
  • 如果我在 application.js 中包含 require("@rails/ujs").start(),则在正文结束之前适用于omniauth。但是,如果我这样做,使用 Shubox 的页面会抛出此错误:“错误:rails-ujs 已加载!”
  • 可以分享application.js和application.html.erb中的head和相关的body部分吗?
  • 已编辑以包含每个文件的相关部分
  • 啊,这与turbolinks有关。将 application.js 移到 head,并监听 turbo load 事件以加载需要 dom 准备好的库,如 shubox

标签: ruby-on-rails ruby-on-rails-6 rails-ujs


【解决方案1】:

由于 Turbolinks,您的 application.js 需要在 head 标签中,otherwise it is evaluated twice。这可能会导致在您初始化它们时期望加载 DOM 的库出现问题 - 我认为这是 shubox 的问题。

所以你应该在你的 application.js 中添加这样的内容(如果你使用的是 Turbolinks 5,对于早期版本,该事件称为 page:load

$(document).on('turbolinks:load',() => {
   new Shubox('#avatar', { key: "abcde-qwerty-12345" })
   }
);

【讨论】:

    【解决方案2】:

    如果您在不同的地方需要它们,您可以随时创建 2 个packs

    javascript/packs/the_one_with_turbolink.js javascript/packs/the_one_with_shubox.js

    那你就可以了

    javascript_pack_tag :the_one_with_turbolinks

    javascript_pack_tag :the_one_with_shubox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多