简体   繁体   English

在HTML(Ruby on Rails)中引用Javascript文件时的必要步骤

[英]Necessary steps when referencing Javascript file in HTML (Ruby on Rails)

I have a javascript file named text_messages.js 我有一个名为text_messages.js的JavaScript文件

The file is already referenced it on my html.erb using <%= javascript_include_tag "text_messages"%> 该文件已经使用<%= javascript_include_tag "text_messages"%>在我的html.erb上被引用了

and it is in the config.assets.precompile 它在config.assets.precompile

when I insert the javascript directly in the html file using <% content_for :javascript do %> <script type="text/javascript"> the code works perfectly fine. 当我使用<% content_for :javascript do %> <script type="text/javascript">将javascript直接插入html文件中时,代码可以正常工作。 Confused as to how i should go about this. 关于我应该怎么做感到困惑。 Thanks! 谢谢!

An issue that occurs regularly is that your app uses Turbolinks but your JavaScript keeps using jQuery's ready event. 经常发生的问题是您的应用程序使用Turbolinks,但是您的JavaScript继续使用jQuery的ready事件。 This only works if the page your JS is running on happens to be the first page you're rendering in the browser. 仅当运行JS的页面恰好是您在浏览器中呈现的第一页时,此方法才有效。

You can check whether or not you're using turbolinks by looking at the application.js file: If it contains //= require turbolinks (or #= require turbolinks if you're using CoffeeScript), you know that you're using it and might be falling into this trap. 您可以通过查看application.js文件来检查是否正在使用涡轮链接:如果它包含//= require turbolinks (或如果使用CoffeeScript则是#= require turbolinks ),则表明您正在使用它可能会落入这个陷阱。

If this is the case, there are three options to solve the issue: 在这种情况下,可以通过以下三种方法解决此问题:

1) Replace all occurrences of the ready event with page:change (or turbolinks:load if you're using Turbolinks 5) which covers both page changes as well as the original ready event. 1)将发生的所有ready事件替换为page:change (如果使用的是Turbolinks 5,则替换为turbolinks:load ),其中包括页面更改以及原始的ready事件。

2) Use the jquery-turbolinks gem . 2)使用jquery-turbolinks gem

3) Remove turbolinks altogether. 3)完全删除turbolink。

Generally, I prefer option 1 since I don't like adding extra gems. 通常,我更喜欢选项1,因为我不喜欢添加额外的宝石。 The only downside is that you have to manually define some events if you're using JavaScript packages that define their own ready events – otherwise they won't be picked up properly. 唯一的缺点是,如果使用的JavaScript包定义了自己的就绪事件,则必须手动定义一些事件-否则将无法正确拾取它们。

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

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