ExecJS::RuntimeError <%= javascript_include_tag 'application', 'data-turbolinks-track' => 真 %>

ExecJS::RuntimeError <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

我正在尝试使用 will_paginate gem 向我的 rails 应用程序添加无限滚动,然后使用 AJAX 获取下一个分页页面,但是我的 javascript 没有被渲染。

问题似乎是 turbolinks 引起的。当我删除 turbolinks 时,错误消失,但脚本不再运行。以下是我的日志和脚本。谁能帮帮我?

这是我从日志中得到的错误:

ActionView::Template::Error (SyntaxError: [stdin]:5:2: unexpected if):
     5:   <!-- had to add the script to override JS error -->
     6:   <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
     7:   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
     8:   <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
     9:   <%= csrf_meta_tags %>
    10: </head>
    11: <body>
  app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb___2390735874352053488_70114430886900'

我的links.js.coffee

jQuery ->

$(window).scroll ->
    console.log('working')
    if $(window).scrollTop() > $(document).height() - $(window).height() - 50
    alert('next page')

现在,如果我取出脚本中将滚动位置与文档高度和 window 高度进行比较的部分,代码就可以工作了。

jQuery ->

$(window).scroll ->
    console.log('working')

如果您需要查看任何其他信息,我很乐意提供。

我觉得这像是缩进问题。 Coffeescript 对空格敏感。尝试

jQuery ->
  $(window).scroll ->
    if $(window).scrollTop() > ($(document).height() - $(window).height() - 50)
      alert('next page')

这里的区别是

  • 缩进 scroll 方法调用 jQuery onReady 函数。
  • if
  • 下缩进alert

至于 turbolinks 问题,您不能简单地使用 jQuery ->(onReady 快捷方式)来加载所有内容。您可能需要添加另一个侦听器。

所以代替:

jQuery ->
  $(window).scroll ->
    ...

您可以尝试这样的操作:

onPageReady = ->
  $(window).scroll ->
    if ...

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

非常像这里描述的:Rails 4: how to use $(document).ready() with turbo-links

希望对您有所帮助。