简体   繁体   English

Rails:包含外部JavaScript

[英]Rails: Include External JavaScript

I want to use a JavaScript library such as a jQuery plugin. 我想使用JavaScript库,如jQuery插件。 Do I use the Rails asset pipeline? 我是否使用Rails资产管道? Or should I include it with a javascript_include_tag? 或者我应该用javascript_include_tag包含它? What are my options and what is the recommended practice? 我有什么选择,推荐的做法是什么?

Will you use the JavaScript library on only a few pages or throughout the application? 您是仅在几页还是整个应用程序中使用JavaScript库? If you will use it throughout the application, use the asset pipeline by adding it to the vendor/assets/javascripts folder. 如果您将在整个应用程序中使用它,请使用资产管道将其添加到vendor / assets / javascripts文件夹。 If you plan to use the library on a single page, use the javascript_include_tag . 如果您打算在单个页面上使用该库,请使用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. app / assets / javascripts /文件夹中逻辑组织站点范围的脚本。

  • Copy external JavaScript libraries (such as jQuery plugins) to the vendor/assets/javascripts folder. 将外部JavaScript库(例如jQuery插件)复制到vendor / assets / javascripts文件夹。

  • List site-wide scripts in the app/assets/javascripts/application.js manifest. 列出app / assets / javascripts / application.js清单中的站点范围脚本。

  • Let the Rails asset pipeline combine them all in one minimized application.js file. 让Rails资产管道将它们全部合并到一个最小化的application.js文件中。

  • For scripts that are used on a few pages that have few visits, load as page-specific JavaScript. 对于在访问次数较少的几个页面上使用的脚本,请加载为特定于页面的JavaScript。

  • Put page-specific JavaScript in the lib/assets/javascripts folder. 将特定于页面的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: 有关所有详细信息的完整说明,请参阅我的文章:

Including External JavaScript Files in Rails 在Rails中包含外部JavaScript文件

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 '文件中。

In Haml 在哈姆尔

= javascript_include_tag "example"

To load the file assets/javascripts/example.js 加载文件assets/javascripts/example.js

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

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