如何提高rails中coffeescript的速度执行速度?

时间:2013-11-05 01:50:24

标签: javascript ruby-on-rails performance coffeescript

为了提高页面加载速度,我通过AJAX实现了创建注释。它很简单而不是重量级。在控制器操作中我有:

def create
    @comment = @commentable.comments.new(params_comment)
    respond_to do |format|
      if @comment.save
        flash.now[:notice] = "Your comment added."
        @response = {comment: @comment, model: @commentable}
        format.js { @response }
        format.html { redirect_to @commentable  }
      else
        format.js { render nothing: :true, status: :not_acceptable }
        format.html { redirect_to @commentable, status: :not_acceptable  }
      end
    end
  end 

和js文件:

$("<%= escape_javascript( render 'comments/comment', @response)%>").appendTo(".comments").hide().fadeIn(500)
$('.notice-wrapper').html("<%= j(render partial: 'shared/notice') %>")
$('.alert').fadeOut(3000)

if $(".no-comments").css("display") is 'block'
  $(".no-comments").hide()
$(".new_answer").hide()
$(".open").show()

但是我没有加快速度,而是产生了相反的效果。通过JavaScript的响应时间增加了100-200毫秒(总共约300毫秒)。这是正常的行为还是我做错了什么?有什么方法可以提高速度吗?

我的表现测试:

enter image description here

UPD: 我只用JS文件进行性能测试。

enter image description here

3 个答案:

答案 0 :(得分:5)

让我暂时搁置一下,我认为在咖啡脚本中嵌入ERB是完全粗略的,无法维护。无可争辩的是,当您在每个请求上生成和编译CoffeeScript时,会产生巨大的性能影响。

您也失去了HTTP缓存的机会。

我的第一个建议是将CoffeeScript与ERB分开。使用您需要的数据填充ERB中的隐藏字段,然后在CoffeeScript中挖掘这些字段。

但是如果你必须在应该是静态文件中嵌入ERB,那么将ERB标签嵌入到纯JavaScript中,然后让编译好的CoffeeScript使用它们。

答案 1 :(得分:1)

您编写的代码并不会真正期望加快请求,因为Rails仍然需要处理所有ERB等。您仍然会返回呈现的HTML并将其发送到添加到其中的浏览器DOM。

如果你想让它“更快”,你可以简单地将@response渲染为json,并使用jQuery或前端框架在客户端处理它。

但是,代码确实使用户更好,因为它不会刷新整个页面。

答案 2 :(得分:0)

我的建议是挂钩表单请求,并在成功时呈现新注释,否则重新呈现表单有错误。一个例子:

# app/javascripts/comments.coffee

$('#comment-form').bind 'ajax:complete', (data, status, xhr) ->
  // psuedo code
  1. if status is success
       append comment -- $('#comments').append(data.comment)
  2. else
       re-render form with errors -- $('#comment-form').html(data.form)
  1. 返回评论模板(评论/评论)并附加评论
  2. 如果not_acceptable,更新您的控制器以返回带有JS响应的表单。
  3. 请注意,该文件位于app / javascripts / comments.coffee
相关问题