1

I have created a new Rails 4 project and I am trying to load an external JavaScript file in my HTML file. I have placed the JavaScript file in the /assets/javascripts directory and included the file in my HTML file.

My HTML file:

<html> <body> <script src="/assets/hello.js"></script> </body> </html> 

My JavaScript file:

document.write("test"); 

I do not see any errors in my web browser console when loading the website. I am pretty sure I put the JavaScript file in to correct directory but the file will not run. Does Rails require something for external JavaScript files to work properly?

I have also tried defining a method in the JavaScript file and calling it within a <script> tag but I get a "Uncaught ReferenceError: methodname is not defined".

    2 Answers 2

    1

    You probably need to list 'assets/hello.js' in application.js. The Rails asset pipeline compiles all JavaScript into application.js based on the filepaths that it finds listed there.

    More info here: http://railsapps.github.io/rails-javascript-include-external.html

    1
    • I have tried that, but after reading the link you provided, //= require_tree . should recursively compile all js files. The js is still not working properly.CommentedFeb 23, 2016 at 6:38
    1

    So I figured out why Rails wasn't loading my JavaScript file. When I created the Rails project, it included .coffee scripts which can be used instead of JavaScript. For some reason by default, the .coffee script was being run instead of the JavaScript file that I created. After deleting the .coffee script, my JavaScript loads as expected.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.