简体   繁体   English

在 Ruby 中包含 JavaScript (on Rails)

[英]Include JavaScript in Ruby (on Rails)

I don't quite understand how Rails includes JavaScript files.我不太明白 Rails 如何包含 JavaScript 文件。 Google and the following documentations didn't solve my problem:谷歌和以下文档没有解决我的问题:
http://railsapps.github.io/rails-javascript-include-external.html http://railsapps.github.io/rails-javascript-include-external.html
http://guides.rubyonrails.org/asset_pipeline.html http://guides.rubyonrails.org/asset_pipeline.html

I understand that Rails uses manifest-files (eg applications.js) to pack every included JavaScript file into one big file (performance reasons, etc.).我知道Rails 使用清单文件(例如applications.js)将每个包含的JavaScript 文件打包成一个大文件(性能原因等)。

In application.html.erb you need to include this manifest, like在 application.html.erb 中,您需要包含此清单,例如

<%= javascript_include_tag :application %>

I added a JavaScript file to /app/assets/ (eg my_javascript.js).我向/app/assets/添加了一个 JavaScript 文件(例如 my_javascript.js)。
So, if I look at the Source-Code, I can find所以,如果我查看源代码,我可以找到

<script src="/assets/application.js" type="text/javascript"></script>

and if I open the file, the content of my_javascript.js is rendered in the application.js file.如果我打开文件,my_javascript.js 的内容将呈现在 application.js 文件中。

My Problem: The function is not working.我的问题:该功能不起作用。 But if I directly include the my_javascript.js in the application.html.erb, like但是如果我直接在 application.html.erb 中包含 my_javascript.js,就像

<%= javascript_include_tag "my_javascript" %>

it is working!这是工作! Of course, it renders a second script-tag, like:当然,它会呈现第二个脚本标签,例如:

<script src="/assets/my_javascript.js" type="text/javascript"></script>

So finally, why does the function work if I include it in specific and not if I use the manifest (how it's supposed to)?所以最后,为什么如果我将它包含在特定中而不是如果我使用清单(它应该如何),为什么该函数可以工作? Do I need to consider something special about the Assets-Pipeline?我是否需要考虑 Assets-Pipeline 的一些特别之处? My manifest includes我的清单包括

//= require_tree .

but I even tried it with但我什至尝试过

//= require my_javascript

I'm on Rails 3.2.3 with Ruby 1.9.3.我在使用 Ruby 1.9.3 的 Rails 3.2.3。

Thank you in advance!先感谢您!

Try putting in Application Layout尝试放入Application布局

<%= yield :head %> in the between head tags. <%= yield :head %>head标签之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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