Rails:包含外部JavaScript [英] Rails: Include External JavaScript

查看:99
本文介绍了Rails:包含外部JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript库,例如jQuery插件.我是否使用Rails资产管道?还是应该在javascript_include_tag中加入它?我有什么选择,推荐做法是什么?

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库?如果要在整个应用程序中使用它,请通过将资产管道添加到 vendor/assets/javascripts 文件夹来使用资产管道.如果您打算在单个页面上使用该库,请使用javascript_include_tag.

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/javascripts folder. If you plan to use the library on a single page, use the javascript_include_tag.

以下是指导您在Rails中使用JavaScript的经验法则:

Here are rules of thumb to guide your use of JavaScript in Rails:

  • app/assets/javascripts/文件夹中逻辑组织您的站点范围脚本.

  • Logically organize your site-wide scripts in the app/assets/javascripts/ folder.

将外部JavaScript库(例如jQuery插件)复制到 vendor/assets/javascripts 文件夹.

Copy external JavaScript libraries (such as jQuery plugins) to the vendor/assets/javascripts folder.

app/assets/javascripts/application.js 清单中列出站点范围的脚本.

List site-wide scripts in the app/assets/javascripts/application.js manifest.

让Rails资产管道将它们全部合并到一个最小化的 application.js 文件中.

Let the Rails asset pipeline combine them all in one minimized application.js file.

对于在访问量很少的几个页面上使用的脚本,请加载为页面特定的JavaScript.

For scripts that are used on a few pages that have few visits, load as page-specific JavaScript.

将特定于页面的JavaScript放入 lib/assets/javascripts 文件夹中.

Put page-specific JavaScript in the lib/assets/javascripts folder.

对于特定于页面的JavaScript,请在​​应用程序布局中使用<%= yield(:head) %>,在视图中使用<% content_for :head ... %>.

For page-specific JavaScript, use <%= yield(:head) %> in the application layout and <% content_for :head ... %> in the view.

有关所有详细信息的完整说明,请参阅我的文章:

For a full explanation with all the details, see my article:

在Rails中包含外部JavaScript文件

Including External JavaScript Files in Rails

这篇关于Rails:包含外部JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆