2

我有一个 Ruby on Rails 应用程序。对于我的观点,我正在使用 react-rails gem。我想通过 Google PageSpeed 提高页面速度。我的主要问题是Remove Render-Blocking JavaScript所以我在我的 javascript_include_tag 辅助方法中添加了 async: true 。然后,当我刷新站点时,我有空白的白色窗口浏览器,其中包含控制台内的这些消息:

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?

4

1 回答 1

1

由于页面上的几乎所有内容都依赖于 JQuery,因此任何成功的页面呈现都需要加载 JQuery 才能启动。因此,根据我的经验,无法绕过阻塞 Javascript。

从用户的角度来看,投入大量工作来防止 JQuery 阻塞可能会允许 DOM 加载,但在 Jquery 和所有相关插件加载后,随着 DOM 被重写,它可能会做很多跳跃,使体验变得更糟比稍微长一点的页面加载。

总体而言,我将集中精力确保您的 JQuery 以及所有相关的 JS 和 CSS 文件通过 CDN 交付,因此您可以从与主域并行的第二个域中受益于 HTTP,并确保您不采取任何措施破坏浏览器缓存 JQuery 和其他资产,因此它们不会阻塞后续请求。

编辑

我还想说的是,值得用预编译的资产进行测试(如果使用 CDN,这无论如何都是必要的),关闭资产实时编译以处理缺失的项目

config.assets.compile = false

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

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

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

4.1.1 远期过期标头

预编译的资产存在于文件系统中,并由您的 Web 服务器直接提供服务。默认情况下,它们没有未来的标头,因此要获得指纹识别的好处,您必须更新服务器配置以添加这些标头。

对于阿帕奇:

# 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>

对于 NGINX:

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

  add_header ETag "";
  break;
}

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

于 2015-09-30T12:23:24.003 回答