The best way to load CSS without page render blocking

There are a lot of ways making web page to load faster. Google created dedicated project for this.(https://developers.google.com/speed/)

One of Google’s suggestion is this: Load css without render blocking. But those methods create another problem. Now i am telling which problem that is and how to solve it.

If your css code is small, Google advices to merge css code to your html, not include spearate css file.
If your css code is large, Google advices to call it via Javascript, in this case css doesn’t cause page render. And web page opens too fast. Well, but what happens when javascript calls CSS file and CSS file is not fully loaded yet?
Yes, webpage seems too ugly for ~0-3 seconds (depends on internet speed) Something like this

 cssload

 

Loading process is short and to hide the first view from visitors is the best way. During that loading we can show to visitors Please wait… or Loading… or something like this.

How to do it?

1. Call all css files via JS (via Google) If you have several css files, you can merge them or you can call all of them separately with followinf JS code.


<script>
      var cb = function() {
        var l = document.createElement('link'); l.rel = 'stylesheet';
        l.href = 'http://yoursite.com/files/style.css';
        var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
      };
      var raf = requestAnimationFrame || mozRequestAnimationFrame ||
          webkitRequestAnimationFrame || msRequestAnimationFrame;
      if (raf) raf(cb);
      else window.addEventListener('load', cb);
    </script>

2. Hide your main screen during loading:

<body class="webbody" style="display:none">

Or

<div class="maincontainer" style="display:none">

3. Put simple loading div out of main container or body.

<div class="loading">Please wait...</div>

4. Make your main content visible and loading div hidden at the end of loaded style.css with putting this kind of code there:

.webbody {display:block} /* or */ .maincontainer {display:block}
.loading {display:none}

That’s all. Now your website renders normally without blocking by css, at the same time when css is loading via JS function, the screen displays please wait… message. You can customize this solution and enrich this functionality, i wrote just simple solution.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.