如何替换文件的结尾<script>在Rails中使用资产管道

How do I replace an end of file <script> with JS in Rails with asset pipeline?

本文关键字:Rails 管道 script 何替换 替换 结尾 文件      更新时间:2023-09-26

所以我有一个HTML文件,我在我的Rails应用程序转置到ERB视图。

然而,在HTML中,我有一个JS片段必须最后运行(在其他所有内容之后),因为它处理页面滚动的方式。

我们有了所有的HTML,然后在</body>之前,我有这个:

<script>
   // Some awesome JS that controls the scrollbar
</script>

但是我还没有弄清楚如何使它在资产管道中工作,遵循Rails惯例,正确。

这个文件是我的Home#Index,它是我的应用程序针对非登录用户的营销网站。

如果我把这个<script>标签放在控制这个Home#Index的布局的顶部,它不起作用。

如果我把这个JS移到app/assets/javascripts/home.js里面,这也不起作用,因为它在加载application.js之前加载了home.js

我也不想把这个放在application.js里面,因为它会干扰其他类在我的应用程序的其余部分类似的命名。

什么是最好的RAILSy方法来做到这一点,而不是在我的app/views/home/index.html.erb里面做<script>JS</script>,因为那感觉不对。

以下步骤可以解决您的问题:

step:1 app/views/home/index.html.erb (provide source of JS.)
<%= javascript_include_tag 'custom/xyz.js', 'data-turbolinks-track' => true %>
step 2: assets/javascrips/custom/xyz.js (JS goes here)
$(function(){
  //js code goes here
});
step 3: application.js  (the require_directory directive which includes all JavaScript files only in the directory specified, without recursion.)
//= require_directory .
step 4: application.rb
config.assets.precompile += %w(custom/*.js)