The right way to include page-specific JavaScript in Rails

后端 未结 5 768
青春惊慌失措
青春惊慌失措 2021-01-03 06:50

I want to include this, for example:

jQuery(document).ready(function($) {
    $(\'#my-modal\').modal(options)
});

In one specific place in

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 07:50

    Given the JS file you want to include is named my_modal.js:

    1. Place your JS files placed in assets/javascripts in some directory inside of assets/javascripts, for example application.

    2. Change line //= require_tree . to //= require_tree application in your application.js (it prevents loading my_modal.js on every page).

    3. Place your my_modal.js in assets/javasctripts

    4. Add my_modal.js to config.assets.precompile array (config assets.precompile += ['my_modal.js']) in your application.rb.

    5. Put javascript_include_tag 'my_modal' in the view you want this file included

    You can go to Rails guides for reference.

提交回复
热议问题