theJava
theJava

Reputation: 15034

Loading javascript files in rails 4

I have a structure in my rails assets directory which is shown below.

--javascripts
 -utils // directory
   helper.js
session.js
app.js
application.js
home.js

This above is my directory structure in rails. When i load my application i get the below error which i feel is the JS is not getting loaded properly.

Uncaught TypeError: Cannot read property 'addMethod' of undefined additional-methods.min.js?body=1:3
Uncaught ReferenceError: Helper is not defined login.js?body=1:22
Uncaught TypeError: Cannot read property 'validate' of undefined 

Below is my application.js

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require vendor
//= require_tree .

Is there anything specific if we have to do for loading files from a specific directory?. How to load the Utils directory and other files in my application.js

Upvotes: 1

Views: 244

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Is there anything specific if we have to do for loading files from a specific directory?

The way to do that is to use the require_directory or require_tree . directives on the other directory:

#app/assets/javascripts/application.js
#= require_tree ./utils 

However, if you're using require_tree ., this will basically include all the directories under your parent (it's called recursion)


As Nicolay has mentioned, you're basically looking to include your JS in the correct order. Although I'm unsure as to why you're getting errors for login.js and additional-methods.min.js

It means your JS is trying to call them, but they are not loaded. This would only cause an error in the likes of precompilation (load order shouldn't be a problem if you're just running in dev)

The answer is to define your manifest as to include the various files when they're needed:

#app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require vendor
//= require bootstrap

But more importantly - how are the functions being called?

Upvotes: 1

nicohvi
nicohvi

Reputation: 2270

From the docs:

Directives are processed top to bottom, but the order in which files are included by require_tree is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest.

So if you need something from Utils to be defined before anything in, say, home.js I'd add require_directory utils above the require_tree . statement. I suppose this could be what's going wrong with your javascript and throwing the errors you posted.

This is what the docs say about require_directory:

You can also use the require_directory directive which includes all JavaScript files only in the directory specified, without recursion.

Upvotes: 3

Related Questions