Timur Gafforov
Timur Gafforov

Reputation: 761

Google pagespeed says to use inline javascript

On my project (Preloaders.net) I have a lot of scripts as it's a web-application. There is no way to have "some" css and js. I merged everything in one file but Google Pagespeed still used to say to remove the "render blocking CSS and JS". So I just made CSS and JS show inline with HTML. Google pagespeed is now happy about the inline CSS, but it really looks stupid - as now the JS and CSS won't be cached on all other pages. Breaking CSS and JS apart is almost useless and impossible as it's all necessary for the web-app to work.

So now I am torn - which is best for user performance: Google "stupidity" or render blocking css and js?

Thanks a lot in advance.

Upvotes: 2

Views: 827

Answers (1)

Tomer Almog
Tomer Almog

Reputation: 3868

Instead of inlining the javascript just load it with defer flag or async:

<script src="whatever.js" async></script>

That will resolve the js issue.

As for css - inline only what is above the fold for each page, and load the rest of the styles in an async manner (from https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery):

<html>
  <head>
  <style>
    .blue{color:blue;}
  </style>
  </head>
<body>
  <div class="blue">
    Hello, world!
  </div>
  <noscript id="deferred-styles">
    <link rel="stylesheet" type="text/css" href="small.css"/>
  </noscript>
  <script>
    var loadDeferredStyles = function() {
      var addStylesNode = document.getElementById("deferred-styles");
      var replacement = document.createElement("div");
      replacement.innerHTML = addStylesNode.textContent;
      document.body.appendChild(replacement)
      addStylesNode.parentElement.removeChild(addStylesNode);
    };
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
        webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
    else window.addEventListener('load', loadDeferredStyles);
  </script>
</body>

Upvotes: 1

Related Questions