Google PageSpeed Insight CSS Javascript "above the fold" issue using CDN

时间:2016-04-04 17:19:46

标签: javascript jquery css twitter-bootstrap google-pagespeed

I tried to implement CDN resources with local fallback support for my webpage. But now I can't get rid of render-blocking JavaScript and CSS CDN resources for jquery and Bootstrap in the "above-the-fold" content.

I tried to stick to Googles Guidelines but it didn't resolve my problem:

<html>

<head>
</head>

<body>
  <div id="wrapper">...</div>
  <!-- jQuery CDN -->
  <script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
  <!-- jQuery local fallback -->
  <script>
    window.jQuery || document.write('<script src="./assets/scripts/jquery-2.2.2.min.js"><\/script>')
  </script>
  <!-- Bootstrap JS CDN -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js</script>
  <!-- Bootstrap JS local fallback -->
  <script>if(typeof($.fn.modal) === 'undefined') {document.write('<script src="./assets/scripts/bootstrap.min.js"><\/script>')}</script>
   <!-- Bootstrap CSS local fallback -->
   <div id="bootstrapCssTest " class="hide "></div>
   <script>
      $(document).ready(function() {
         if ($('#bootstrapCssTest').is(':visible') === true) {
              $("head ").append('<link rel="stylesheet " href="./assets/styles/bootstrap.min.css">');
         }
      });
    </script>
    </body>
</html>
<!-- Bootstrap CSS CDN -->
<link rel="stylesheet " href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css ">

UPDATE: I tried to use the "async/defer" attribute for loading my .js CDN scripts. But it didn't work as my local fallback script gives me "Uncaught ReferenceError: $ is not defined" error because they are executed before jquery async loading had been finished.

1 个答案:

答案 0 :(得分:0)

  1. 使用jQuery库包括页脚部分和下面的自定义代码启动jquery代码
  2. 40%的CSS代码在首屏内容(使用内部样式表的头部)<style type="text/css">...</style>
  3. <html>
    
    <head>
    </head>
    
    <body>
      <div id="wrapper">...</div>
      <div id="bootstrapCssTest" class="hide"></div>
      <!-- jQuery CDN -->
      <script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
      <!-- jQuery local fallback -->
      <script src="../scripts/jquery-2.2.2.min.js"></script>
      <!-- Bootstrap JS CDN -->
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
      </script>
      <!-- Bootstrap JS local fallback -->
      <script src="../scripts/bootstrap.min.js"></script>
      <!-- Bootstrap CSS local fallback -->
      <script>
        $(document).ready(function() {
          if ($('#bootstrapCssTest').is(':visible') === true) {
            $("head ").append('<link rel="stylesheet " href="./assets/styles/bootstrap.min.css">');
          }
        });
      </script>
      <!-- Bootstrap CSS CDN -->
      <link rel="stylesheet " href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css ">
    </body>
    </html>