使用 react-rails gem 移除 rails 中的渲染阻塞 javascript

Remove render blocking javascript in rails with react-rails gem

我在 Rails 应用程序上有一个 Ruby。对于我的观点,我正在使用 react-rails gem。 我想通过 Google PageSpeed 提高 pagespeed。我的主要问题是 移除渲染阻塞 JavaScript 所以我添加了 async: true 到我的 javascript_include_tag 辅助方法。然后当我刷新网站时,我有空白的白色 window 浏览器,控制台内有这些消息:

ReferenceError: $ is not defined
   $(document).ready(ready);
ReferenceError: jQuery is not defined
   }(jQuery);

ReferenceError: jQuery is not defined
   })( jQuery );

ReferenceError: React is not defined
    this.About = React.createClass({

我的 applicaton.js 文件:

//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require react
//= require react_ujs
//= require semantic-ui
//= require components
//= reqiore custom
//= require_tree .

var ready;
ready = function() {

};

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

我需要做什么才能消除阻塞javascript?

由于页面上几乎所有内容都依赖于 JQuery,因此任何成功的页面渲染都需要加载 JQuery 才能开始。因此,根据我的经验,没有办法绕过阻塞 Javascript。

从用户的角度来看,投入大量工作来防止 JQuery 阻塞可能允许 DOM 加载,但它可能会在 [=45= 之后进行大量跳转] 并且所有相关插件都已加载 DOM 被重写,这使得体验比稍长的页面加载更糟糕。

总的来说,我会集中精力确保您的 JQuery 和所有相关的 JS 和 CSS 文件都通过 CDN 传送,这样您就可以从并行的第二个域的 HTTP 中获益到你的主要,并确保你没有做任何事情来破坏 JQuery 和其他资产的浏览器缓存,这样它们就不会在后续请求时阻塞。

编辑

我还想提一下,使用预编译的资产进行测试是值得的(如果使用 CDN,无论如何这是必要的),关闭资产实时编译以查找缺少的项目

config.assets.compile = false

这将防止任何丢失的资产导致令人困惑的延迟,以及在您上线后可能无效的编译。

关于从您的网络服务器提供资产的附加说明:

根据http://guides.rubyonrails.org/asset_pipeline.html

4.1.1 Far-future Expires Header

Precompiled assets exist on the file system and are served directly by your web server. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add those headers.

For Apache:

# The Expires* directives requires the Apache module
# `mod_expires` to be enabled.
<Location /assets/>
  # Use of ETag is discouraged when Last-Modified is present
  Header unset ETag
  FileETag None
  # RFC says only cache for 1 year
  ExpiresActive On
  ExpiresDefault "access plus 1 year"
</Location>

For NGINX:

location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;

  add_header ETag "";
  break;
}

最后,请确保在模拟最终生产环境的服务器上测试 运行,因为 Rails 开发服务器不会提供相同的响应能力。