Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove critical CSS from the main.css file

I am working hard to imporove page speed. I am using Critical Path CSS Generator tool to identify above-the-fold CSS. Then I inline critical CSS as suggested, and load the full css asynchronously.

But I end up with a lot of duplicate CSS that way, which is not so optimal. So my question is:

How to remove critical CSS from the main.css file?

Thanks in advance.

like image 785
Damian Pavlica Avatar asked Dec 04 '15 21:12

Damian Pavlica


People also ask

What is a critical CSS?

Critical CSS (or critical path CSS) is the CSS applied to above-the-fold elements. Put simply, it's the CSS responsible for content that's immediately visible when a user opens your website. A few things to unpack here. First, above-the-fold is the part of a page that users see without scrolling.


1 Answers

While it may seem like an anti-pattern, all above-the-fold CSS you inline into your document SHOULD be duplicated in your external CSS document. That way, you can make a single site-wide bundle that can be fetched once for your entire site, but that initial page load will be accelerated. While this does result in extra "wasted" KBs upfront, the advantage is that you have a small subset of the necessary CSS available to you as soon as the HTML is sent to the client, reducing the time it takes to render the client's initial view.

Also, to be clear, if you're following this practice correctly, every page on the site will have a different set of above-the-fold css, because every page has different content/tags above-the-fold which would make it impossible to remove the above-the-fold CSS from the full external file (assuming you're concatenating all CSS into one file).

You can read more about the practice of above-the-fold css here.

If you're really concerned about code duplication (though you shouldn't be in this case), you can use cookies to keep track of whether or not a user has visited the site before. If the user has not been before, then you can inline the above-the-fold CSS. If the user has been before, you can assume that the user already has the full CSS file and that the CSS file will be pulled from the browsers cache.

There are a bunch of articles on how unreliable the browser cache is, so my recommendation is that you simply do what you're already doing to satisfy client requirements.

Another thing that should be mentioned is that this practice will largely go away once HTTP/2 becomes more prevalent as subsequent HTTP requests won't be nearly as expensive as they are today. Considering the intensive tooling/effort this practice requires (especially when future proofing against HTTP/2), it may be better (I think it is) to just avoid it completely.

like image 73
Benjamin Solum Avatar answered Sep 30 '22 18:09

Benjamin Solum