0

I'm trying to load some JavaScript in my rails application like so:

Application.html.erb (in the head)

<%= javascript_include_tag 'application' %>

Application.html.erb (before end of HTML)

<script>
  $(document).ready(function() {
    notie.alert(1, "It Works", 2);
  });
</script>

Application.js

//= require rails-ujs
//= require turbolinks
//= require theme/jquery
//= require theme/bootstrap
//= require theme/select2
//= require theme/notie
//= require theme/plugins
//= require theme/app
//= require_tree .

With this set up, I'm getting the following errors:

TypeError: document.body is null
TypeError: notie is undefined

It seems to me that the error may be because of turbolinks and how the JS is loaded with the asset pipeline but for the life of me I can't figure out where it's going wrong. Any help is appreciated.

Amz
  • 13
  • 1
  • 1
  • 3
  • Have you tried removing `//= require_tree .` and moving `//= require turbolinks` to the bottom? – Okomikeruko Mar 22 '18 at 16:25
  • Yup I've tried that. No dice. – Amz Mar 22 '18 at 16:32
  • Have you tried creating a new .js file, filling it with the `//= require` of the new assets, and putting `<%= javascript_include_tag 'new' %>` before the closing body tag? https://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript – Okomikeruko Mar 22 '18 at 16:42
  • 1
    Did this, added the new file to precompile in the assets.rb and got it working! Cheers friend – Amz Mar 22 '18 at 17:08

1 Answers1

0

The problem seems to be that your Javascript is calling for a <body> tag before it exists in the DOM. That's why you're getting the error:

TypeError: document.body is null

For Javascript like that it's best to load it at the bottom of the page instead of the Head.

Okomikeruko
  • 1,123
  • 10
  • 22