JavaScript库在Rails中加载两次 [英] JavaScript library loads twice in Rails
问题描述
当我将JavaScript库添加到Rails资产文件夹并使用以下命令在我的erb文件中配置时:
<%= javascript_include_tag('scripts.js')%>
,包含与JavaScript文件关联的类的HTML代码加载两次。
When I add the JavaScript library to the Rails asset folder and have it configured in my erb file using:
<%= javascript_include_tag('scripts.js') %>
, the HTML code with the classes associated with the JavaScript file load twice.
我附上了一个示例这里。当我将JavaScript文件链接到公共文件夹时,这个问题不会发生,而是JavaScript不会出现。
I have attached an example here. When I link the JavaScript files to the public folder this issue does not happen, but instead the JavaScript does not show up.
JavaScript
$(function() {
$("a.page-scroll").bind("click", function(a) {
var b = $(this);
$("html, body").stop().animate({
scrollTop: $(b.attr("href")).offset().top
}, 1500, "easeInOutExpo"), a.preventDefault()
})
})
Html.erb
<li>
<a class="page-scroll" href="#portfolio">Portfolio</a>
</li>
<li>
<a class="page-scroll" href="#me">About Me</a>
</li>
<li>
<a class="page-scroll" href="#contact">Contact</a>
</li>
没有相关的控制台错误。
There are no relevant console errors.
注意:如果没有Rails,这个工作完全正常。
Note: This works perfectly fine without Rails.
推荐答案
如果它是一个开箱即用的标准rails项目,javascript / coffee文件存在于lib / assets / javascripts或vendor / assets / javascripts中,然后它将通过application.js文件中的这一行自动被拉入rails资产管道:
If its a standard rails project out of the box, and the javascript/coffee file lives inside lib/assets/javascripts or vendor/assets/javascripts then it will automatically be pulled into rails asset pipeline via this line in the application.js file:
// = require_tree。
//= require_tree .
如果被拉入,则无需在erb文件中使用javascript_include_tag通过application.js(我假设application.js是由一些布局文件通过javascript_include_tag('application')呈现的,这就是它渲染两次的原因。)
There is no need to use the javascript_include_tag inside the erb file if its pulled in by application.js (I am assuming that application.js is being rendered by some layout file via javascript_include_tag('application'), this is why its rendering twice).
如果js文件位于其中一个目录中,并从erb文件中删除了javascript_include_tag ....它应该解决你的双重渲染问题。
If the js file lives in one of these directories, and you remove your javascript_include_tag from the erb file.... It should solve your double render problem.
这篇关于JavaScript库在Rails中加载两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!