javascriptruby-on-railshotwire-railsturbo

Turbo: how to re-evaluate some js files after render?


I'm still pretty new to Hotwire. I have this issue, which I think is a common issue with Turbo. I remember I had it before with Turbo-Links, this is because I ended up deactivating it always on my projects.

The problem seems to be that the .js files are not re-evaluated after the Frame is loaded.

These JS have some after-render logic, like the Bootstrap "tooltips", which requires a query selector to go through all the elements that match and activate the functionality.

I have been searching in Google with no luck:

How can I ask Turbo to reevaluate some of my js files imported with javascript_include_tag like in here?:

<%= javascript_include_tag "phoenix/vendors/dayjs/dayjs.min.js" %>
<%= javascript_include_tag "phoenix/assets/js/phoenix.js" %>

I was expecting something like:

<%= javascript_include_tag "phoenix/assets/js/phoenix.js", turbo_reload: true %>

Solution

  • You are probably looking for a turbo:frame-load listener.

    Here's an example:

    document.documentElement.addEventListener('turbo:frame-load', function (e) {
      // Initialize bootstrap tooltips and other logic here
    });
    

    Source: https://turbo.hotwired.dev/reference/events