Rails:包括外部 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12531783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: Include External JavaScript
提问by Daniel Kehoe
I want to use a JavaScript library such as a jQuery plugin. Do I use the Rails asset pipeline? Or should I include it with a javascript_include_tag? What are my options and what is the recommended practice?
我想使用 JavaScript 库,例如 jQuery 插件。我是否使用 Rails 资产管道?或者我应该将它包含在 javascript_include_tag 中?我有哪些选择,推荐的做法是什么?
回答by Daniel Kehoe
Will you use the JavaScript library on only a few pages or throughout the application? If you will use it throughout the application, use the asset pipeline by adding it to the vendor/assets/javascriptsfolder. If you plan to use the library on a single page, use the javascript_include_tag
.
您会只在几个页面上还是在整个应用程序中使用 JavaScript 库?如果您将在整个应用程序中使用它,请通过将其添加到vendor/assets/javascripts文件夹来使用资产管道。如果您打算在单个页面上使用该库,请使用javascript_include_tag
.
Here are rules of thumb to guide your use of JavaScript in Rails:
以下是指导您在 Rails 中使用 JavaScript 的经验法则:
Logically organize your site-wide scripts in the app/assets/javascripts/folder.
Copy external JavaScript libraries (such as jQuery plugins) to the vendor/assets/javascriptsfolder.
List site-wide scripts in the app/assets/javascripts/application.jsmanifest.
Let the Rails asset pipeline combine them all in one minimized application.jsfile.
For scripts that are used on a few pages that have few visits, load as page-specific JavaScript.
Put page-specific JavaScript in the lib/assets/javascriptsfolder.
在app/assets/javascripts/文件夹中以逻辑方式组织站点范围的脚本。
将外部 JavaScript 库(例如 jQuery 插件)复制到vendor/assets/javascripts文件夹。
在app/assets/javascripts/application.js清单中列出站点范围的脚本。
让 Rails 资产管道将它们全部合并到一个最小化的application.js文件中。
对于在访问量很少的几个页面上使用的脚本,请加载为特定于页面的 JavaScript。
将特定于页面的 JavaScript 放在lib/assets/javascripts文件夹中。
For page-specific JavaScript, use <%= yield(:head) %>
in the application layout and <% content_for :head ... %>
in the view.
对于特定于页面的 JavaScript,请<%= yield(:head) %>
在应用程序布局和<% content_for :head ... %>
视图中使用。
For a full explanation with all the details, see my article:
有关所有细节的完整解释,请参阅我的文章:
回答by Shehryar
To access Javascript on a single file, javascript_include_tag
is the best option.
要在单个文件上访问 Javascript,javascript_include_tag
是最好的选择。
With that what you can do is too add 'Rails.application.config.assets.precompile += %w( yourfilename.js )
' to your 'config/initializers/assets.rb
' file.
有了这个,您可以做的也就是将 ' Rails.application.config.assets.precompile += %w( yourfilename.js )
'添加到您的 ' config/initializers/assets.rb
' 文件中。
回答by Apoorv Agarwal
In Haml
在哈姆
= javascript_include_tag "example"
To load the file assets/javascripts/example.js
加载文件 assets/javascripts/example.js