Using Rails 3.1, where do you put your “page specific” JavaScript code?

前端 未结 29 1808
一生所求
一生所求 2020-11-22 11:08

To my understanding, all of your JavaScript gets merged into 1 file. Rails does this by default when it adds //= require_tree . to the bottom of your appl

29条回答
  •  北海茫月
    2020-11-22 11:45

    I have another solution, which although primitive works fine for me and doesn't need any fancy selective loading strategies. Put in your nornal document ready function, but then test the current windows location to see if it is the page your javascript is intended for:

    $(document).ready(function() {
       if(window.location.pathname.indexOf('/yourpage') != -1) {
              // the javascript you want to execute
       }
    }
    

    This still allows all the js to be loaded by rails 3.x in one small package, but does not generate much overhead or any conflicts with pages for which the js isn't intended.

提交回复
热议问题