Max Rhan
Max Rhan

Reputation: 345

Is it okay to change the loading order of JavaScript files in Rails 4?

In my application.js.coffee I define some overarching functions which I use in my other JavaScript files. So far this was no problem, because except in application.js.coffee most of the code was wrapped in document ready $ ->

Now I am optimizing loading time, for instance running AJAX requests outside of $ -> to start the data loading beforehand.

Now I need the functions I have defined, which are of course not available since application.js.coffee is loaded at the very end. To solve this I replaced

 #= require_tree .

with

 #= require_self
 #= require_tree .

Is this the way to do it, or is that proscribed?

Upvotes: 0

Views: 105

Answers (1)

Gjaldon
Gjaldon

Reputation: 5644

That's how it's usually done. You'd have to require application.js.coffee before requiring your other custom javascript files(which are loaded with require_tree). Make sure though that application.js.coffee's plugin dependencies are loaded before the require_self.

For example, if you use jQuery, you'd do it this way in your application.js.coffee

#= require jquery
#= require_self
#= require_tree .

Upvotes: 1

Related Questions