0

I want to have a JavaScript file available for a view in my Rails app.

// app/javascript/custom/manage.js

document.body.style.backgroundColor = 'lightblue'
const test = document.getElementById('test')
# config/importmap.rb

pin_all_from "app/javascript/custom", under: "custom"
# app/views/locations/manage.html.erb

<%= javascript_include_tag "custom/manage", defer: true %>

When I navigate back to the manage view, I am getting the following error:

Uncaught SyntaxError: redeclaration of const test

I suspect this is because of how Turbo works. Because I tried commenting it out in the application.js file and the error was gone.

1
  • @mechnicov Tried it now and it didn't work. (Failed to register controller: hello (controllers/hello_controller and Uncaught DOMException: Node.removeChild: The node to be removed is not a child of this node on refresh). javascript_import_module_tag works as it doesn't load the JavaScript on subsequent visits to the page - but that's a bug for me because I want the JS to be associated to with the view and run everytime I visit the view rendered by manage.html.erb Commented Oct 12, 2023 at 17:42

1 Answer 1

0

As I understand, you need selective import modules feature

It's possible to selectively import modules on specific pages, add at the top of your view using content_for

<%# app/views/locations/manage.html.erb %>

<% content_for :custom_js do %>
  <%= javascript_import_module_tag "custom/manage" %>
<% end %>

And in the layout

<%= javascript_importmap_tags %>
<%= yield(:custom_js) %>

javascript_importmap_tags should be first

Sign up to request clarification or add additional context in comments.

5 Comments

This works for the initial page load. But when I navigate away from the page, and then come back to it, the JavaScript stops working.
@Alabhya did you try to wrap you script with event handler? document.addEventListener('turbo:load', () => { document.body.style.backgroundColor = 'lightblue'; const test = document.getElementById('test') })
Yes. I get Uncaught TypeError: input is null when I navigate to a different page.
What is input? There is no any input in the question
Sorry. I added a input field and attached an event listener to it for the click event, in addition to the code in the question. Looks like the JavaScript file is loaded once and then used for all the views, once loaded - causing the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.