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

Fas*_*ian 1 javascript performance ruby-on-rails 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 
Run Code Online (Sandbox Code Playgroud)

和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()
Run Code Online (Sandbox Code Playgroud)

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

我的表现测试:

在此输入图像描述

UPD: 我的性能测试只用JS文件.

在此输入图像描述

Vid*_*dya 5

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

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

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

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