简体   繁体   English

在Rails App中加载JavaScript

[英]Loading JavaScript in Rails App

I'm trying to initiate a JS file when clicking on a link "link_to" in my rails app. 当我在Rails应用程序中单击链接“ link_to”时,我正在尝试启动JS文件。

I ensured the the asset pipeline is working correctly by testing with 我通过进行以下测试来确保资产管道正常运行

$(document).ready(function() {
    alert("test");
});

and the alert popups without a problem. 并且警报弹出窗口没有问题。

However, the script only loads when I refresh after the page is loaded. 但是,该脚本仅在加载页面后刷新时加载。 I've tried the code below without any luck but as I said, it works once the page is reload. 我已经尝试了下面的代码,但是没有运气,但是正如我所说的,一旦重新加载页面,它就可以工作。

var ready;
ready = function() {

  //My JS Code

};

$(document).ready(ready);
$(document).on('page:load', ready);

I have the Turbolinks gem file complied Gem file below 我有下面的Turbolinks gem文件符合Gem文件

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require jquery.slimscroll
//= require app
//= require zopim
//= require turbolinks

I'm sure it's something small I'm missing. 我确定这是我所缺少的小东西。 I've seen examples using coffee script but I don't know enough about it to use it at this time. 我已经看到了使用咖啡脚本的示例,但是我现在对此尚不了解。

Edit: 编辑:

While monitoring Network under Chrome Dev tools, I noticed that none of the JS load until I hit F5 to reload the page but I don't seem to have problems with the other scripts. 在使用Chrome Dev工具监视Network时,我注意到直到我按下F5重新加载页面之前,都没有加载JS,但是其他脚本似乎没有问题。 This might be a separate issue. 这可能是一个单独的问题。

也许试试这个?

$(document).on('turbolinks:load', ready);
$(document).on('turbolinks:load', function() {
  //My JS Code
}) 

This should work for you. 这应该为您工作。

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

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