Rails 6 & turbolinks: 'turbolinks:load' fires before new \<head> scripts are loaded

Viewed 600

I have a Rails 6 project. When a page is loaded using turbolinks the turbolinks:load event fires before <head> scripts are merged in and executed. Eventlisteners in those scrips never get executed because they are added after the event has happened.

For example a page with the following in the <head> section of the layout:

    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload', defer: 'defer'
    = yield :extra_head

And this at the top of the page:

- content_for :extra_head do
  = javascript_pack_tag 'club_edit'

Produces this html:

<script src="/packs/js/application-629a480faedfc40e8948.js" data-turbolinks-track="reload" defer="defer"></script>
<script src="/packs/js/club_edit-8d7d256609de3b852df1.js"></script>

The club_edit.js file adds a listener to turbolinks:load to call a function called init()

document.addEventListener('turbolinks:load', init);

When I load the page 'normally' this works as expected and the init() function gets called. But if I load it from a turbolinks link, it does its xhr call and the turbolinks:load event fires before the listener gets added.

What should I be doing to make sure the init() funtion gets called either way?

0 Answers
Related