开发者

In Ruby on Rails, what if a view needs to use jQuery that is loaded at the end of application layout?

开发者 https://www.devze.com 2023-02-25 06:20 出处:网络
One recommended practice is to load jQuery at the end of application layout: = yie开发者_开发知识库ld

One recommended practice is to load jQuery at the end of application layout:

= yie开发者_开发知识库ld

= render 'shared/footer'

= javascript_include_tag 'jquery'

so that page rendering is faster without the hinderance of Javascript or jQuery. But what if there are some particular things that each view needs to do? For example, the index view need to do something, and the show view needs to do something else, and so the Javascript code would either be inside those view templates or be included from those view templates, but at this point, the jquery.js file is not loaded yet (not until near the end of page)? The jquery.js can be loaded before the yield, but then it is way in front of the page.


Your could use the content_for

In layout

yield
render 'footer'
javascript_include_tag 'jquery'
yield :custom_javascript

In views

<%= content_for :custom_javascript do %>
<script type="text/javascript">alert(jQuery)</script>
<% end %

http://guides.rubyonrails.org/layouts_and_rendering.html#using-content_for


Fonsan is right. Plus remember to check your dom is loadedwhen you use jQuery.

So wrap it this way:

$(function(){
   // your js code here
});
0

精彩评论

暂无评论...
验证码 换一张
取 消