我同意 apneadiving.. 就个人而言,js.erb 调用增加了很多认知开销。我所做的是将我的 javvavscripts 加载到部分布局中
*app/views/layouts/_javascripts.html.haml
= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js'
= javascript_include_tag "http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js"
= include_javascripts :app
= hoptoad_javascript_notifier
= yield :javascripts
然后我使用Jammit gem 中的jammit 命令来缩小,并压缩我的 js 和 css 资产
config/assets.yml
javascripts:
app:
- public/javascripts/rail.js
- public/javascripts/underscore-min.js
- public/javascripts/jquery.dump.js
- public/javascrippts/etc*.js
每个页面需要自定义页面级js,我在页面底部扔了一个content_for :javascripts块:
app/views/something/awesome.html.haml
%h1 cool page
Other cool stuff
- content_for :javascripts do
:javascript
$(document).ready(function(){
console.log('This document is REaDY!! and, this page rocks');
$.ajax({
url: "#{new_item_path(@item)}", //ruby is evaluated due to string interpolation
success: function(data) {
console.log('Loaded ' + data + ' from ' + #{new_item_path(@item)})
}
});
};
这让我可以在application.html.haml 布局的底部找到一个render 'layouts/javascripts',并且我的所有javascript geets 都通过管道传输到页面底部,因此加快页面加载速度为suggested here by Yahoo 这也让我可以使用如果需要,erb 从 Rails 为页面级 js 生成变量