如何在 rails 中安装砌体或其他 javascript? (不使用宝石)

How do I install masonry or other javascript in rails? (not using gems)

我想要Masonry for my Rails 4.2 project and initially installed it via the masonry-rails gem and then wasted an evening until I realized that the gem was using an outdated version of Masonry. This will be my first attempt to add javascript to my Rails app without a gem. From the installation docs选项是:下载CDN包管理器(bower/npm)

我使用 CDN 只需添加

<script src="https://npmcdn.com/masonry-layout@4.1/dist/masonry.pkgd.min.js"></script>

到将使用该脚本的我的 index.html.erb 视图文件的顶部。这个对吗?

使用 CDN 而不是 下载 包管理器[=33] 的 advantage/disadvantage 是什么=] 如果我想手动将 masonry.pkgd.min.js 添加到我的项目中,我该怎么做?

This has some good related info

What is the advantage/disadvantage of using CDN instead of Download

要了解 CDN 与本地脚本的优缺点,请查看答案 herehere

How to manually add them in project

有两种方法

  1. 将它们(例如 masonry.pkgd.min.js)放在 app/assets/javascripts 下,并在 application.js 中要求它们作为 //= require masonry.pkgd.min.js,但前提是您没有这个line //= require_tree .因为require_tree会加载app/assets/javascripts文件夹下的所有js文件

  2. 或放在vendor/assets/javascripts中。但在这种情况下,您必须在 application.js 文件

  3. 中要求它

added masonry script to the top of index.html.erb view file that will use the script. Is this correct?

它是正确的,因为它只会加载到那个特定的视图。现在,如果您将相同的内容放入 application.html.erb 或通过资产加载它,那么相同的 js 脚本将加载到每个视图中。