简体   繁体   中英

Coffescript getting executed on all pages

I have a function in my coffeescript "students.coffee":

$(document).ready ->
   ...

The problem is that this is getting loaded on all pages loads. Is there any way I can restrict this function to run only on the view for a particular action of a specific controller?

Or Is there a way I can explicitly call this method from the specific view?

First of all, I highly recommend you to read the Asset Pipeline documentation to understand it better.

By default, in application.js there's a directive require_tree that will load all js files that are in the same folder and sub-folders of the application.js file.

That means, that all controller's JS created automatically by Rails generators are going to be added to the compressed application.js file and then be executed on every page, since application.js is declared on the top of you layout ( application.html.erb ).

If you want specific controller's asset, take a look a this part of the Asse Pipeline documentation.

First remove students it from your application.js manifest file. I'm assuming you don't have //= require_tree . . Or that will load everything.

In your specific view where you want to load this file, you can write like this

<%= javascript_include_tag 'students', 'data-turbolinks-track' => true %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM