I'm not sure about the reading order of javascript files in rails6, so please let me know.

Current status

I want to get the DOM element with the following code, but I'm having trouble getting it. (When I looked at conslole.log, nill was returned.)

const flashMsg = document.querySelector ('.flash-message')

When I was investigating, if the Javascript file was read first, I could not get the element
I found that nill was returned.
As a workaround, it is necessary to write to read Javascript at the end of the body tag, but in application.html.erb, the reading code of the js file is written in the head tag, so javascript is first Will it be read? I am wondering.


<! DOCTYPE html>
  <% = csrf_meta_tags%>
  <% = csp_meta_tag%>
  <% = stylesheet_link_tag'application', media:'all','data-turbolinks-track':'reload'%>
// Isn't Javascript loaded before loading the body tag here?
  <% = javascript_pack_tag'application','data-turbolinks-track':'reload'%>
  <% = yield%>

When reading Javascript individually, at the end of the target file (.erb file)<% = javascript_pack_tag'filename'%>I think I should write, but what should I do if I want to get the DOM element in a common file?
I'm sorry I couldn't explain it well, but if anyone can understand it, please let me know.
Thank you.

Development environment
  • Rails
  • ruby 2.6.5
  • Answer # 1

    In a way that comes to mind

    = javascript_pack_tag'application', defer: true


    window.onload = function () {
      const flashMsg = document.querySelector ('.flash-message');

    Is it?
    The former has not been confirmed to work, so the latter is recommended.
    How is it?