Loading position of javascript in rails app

1.2k Views Asked by At

There are two pieces of my application that seem to require that I load my javascript at different points.

  1. Omniauth works when I place <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' within <head></head>.
  2. Shubox (js library used to upload photos) works when I place <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' just before </body>.

Each of the two does not work when the javascript is loaded where the other requires. So, if I place the javascript line at the end of the body, omniauth does not work.

I can provide additional information if needed. Thank you in advance.

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>
2

There are 2 best solutions below

0
On

Because of Turbolinks your application.js needs to be in the head tag, otherwise it is evaluated twice . This can cause a problem with libraries that expect your DOM to be loaded when you initialize them - which I think is your problem with shubox.

So you should put something like this in your application.js (if you are using Turbolinks 5, for earlier version the event is called page:load)

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

You can always create 2 packs if you need them in different places:

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

then you can do

javascript_pack_tag :the_one_with_turbolinks

and

javascript_pack_tag :the_one_with_shubox