Connect with us

Building a Faster Web: Working With Critical CSS

coding

Building a Faster Web: Working With Critical CSS

As a web developer your job is to provide a smooth and fast web experience. The most important part of making a website is to know exactly how the website is doing. You develop HTML, CSS and JavaScript for a website but you should know how your website is providing web pages from those. Here is something for you to know how to speed up the rendering of your web pages.

Normally when someone wants to check and improve the performance of their websites they visit to Google’s PageSpeed Insights tool which is very useful and easy to use. But sometimes you may get confused to see the suggestion because CSS and JavaScript block the rendering of your page. Don’t worry I have a simple solution for that. Let’s get to know about working with critical CSS.

What is Critical CSS

When you create a webpage using CSS, it normally calculate the layout of the page that’s why it takes time to execute all the CSS files given in the <head> of the page. In that case it takes time to load the whole page. This is not good at all for you because if you use a huge CSS file then your users would find it a lot time consuming to download. There is good news for you that there is a technique called critical rendering path to optimize the delivery of your CSS.

When a browser renders a page, it does it step by step and you may know those steps by the technique. You need to know the critical CSS that is needed to represent your page to the users. When a user loads a page for the first time, that’s the critical part of a webpage what he sees. So they need to load the minimum amount of CSS which is required to render the top portion of the page across all breakpoints. Your job is to find out the critical CSS you need for your page. You have to observe the web page’s DOM and find out the list of styles that are responsible in view. So you need to do things that are not simple manually. I have something for you in this regard.

Working with Critical CSS

Let’s change the way you normally handle CSS and then start working with it. At first split it into two files. For the first one, before inlining the minimum set of CSS in the webpage, extract it to render the above-the-fold content. For the second one, load it for not blocking the webpage. If you inline critical CSS into your HTML, you can get rid of the additional round-tips in the critical path. In this way you may provide a quick service to the users. Take a look at the code now:   


<!doctype html> 
<head> 
<style> /* inlined critical CSS */ </style> 
<script>loadCSS('non-critical.css'); </script> 
</head> 
<body> 
  ...body goes here 
</body> 
</html> 

Now let’s talk about what exactly happens there. You may think about why you would manually inline a snipet of CSS in every page. Don’t worry; you don’t have to do it rather it can be done automatically by a tool named Critical. It’s a Node.js package that will automatically extract and inline critical path CSS in HTML. I am naming another tool Grunt for you. It’s a JavaScript task runner that will automatically process the CSS. You have to combine both the tools

Let’s Start

First of all, fire up the Node.js console and navigate it to your website path. Then you have to install the Grunt command line interface by typing the command into your console given below.

npm install -g grunt-cli
Now install the Grunt task runner:

npm install grunt –save-dev

Then the grunt-critical12 plugin:

npm install grunt-critical –save-dev

Now you have to create a Gruntfile containing the task configuration for your project. Code will be:

module.exports = function (grunt) {
 grunt.initConfig({
 critical: {
 dist: {
 options: {
 base: './'
 },
 // The source file
 src: 'page.html',
 // The destination file
 dest: 'result.html'
 }
 }
 });
 // Load the plugins
 grunt.loadNpmTasks('grunt-critical');
 // Default tasks.
 grunt.registerTask('default', ['critical']);
 }; 


If you take a closer look at the code, you will see that I configured the critical plugin. Then the CSS will be processed against the given page and then it will calculate the critical CSS. And finally the critical CSS will be inlined and the HTML page will be updated. Now, run the plugin by typing grunt into the console. Actually that plugin uses PhantomJs which is a headless WebKit browser. It captures the required critical CSS. So, it’s able to load your webpage and test for the optimal critical CSS. Then you will be able to provide different screen dimensions.


critical: { 
dist: { 
options: { 
base: './', 
dimensions: [{ 
width: 1300, 
height: 900 
      }, 
      { 
width: 500, 
height: 900 
      }] 
    }, 
files: [ 
      {src: ['index.html'], dest: 'dist/index.html'} 
    ] 
  } 
}  

If you write the code above then it will process the file you gave against multiple dimensions and it will inline Critical CSS. In that case you will be able to provide a better experience no matter which screen size they use. So this is more important for mobile users.

Use of Critical

I said earlier that this tool helps to extract and inline critical CSS automatically and you don’t have to change your website style for it. When you use this tool you can normally update files or everything, nothing to worry about. Just keep one thing in mind that you have to run Grunt every time you make any change to your CSS files.

Now I will show you a code that will show you how you can process the critical CSS for multiple files or an entire folder. Then you have to update your Gruntfile:


critical: { 
dist: { 
options: { 
base: './', 
dimensions: [{ 
width: 1300, 
height: 900 
       }, 
       { 
width: 500, 
height: 900 
      }] 
    }, 
files: [ 
      {src: ['index.html'], dest: 'dist/index.html'}, 
      {src: ['blog.html'], dest: 'dist/blog.html'} 
      {src: ['about.html'], dest: 'dist/about.html'} 
      {src: ['contact.html'], dest: 'dist/contact.html'} 
    ] 
  } 
} 

If you want to run the task against every HTML file in a given folder:


critical: { 
dist: { 
options: { 
base: './', 
dimensions: [{ 
width: 1300, 
height: 900 
      }, 
      { 
width: 500, 
height: 900 
      }], 
src: '*.html', 
dest:  'dist/' 
    } 
  } 
}

This sample shows how to archive across your website.

Test finally

Whatever you make, testing is necessary to be satisfied and also to find out the mistakes. Earlier in this article I told about a tool that you may use for testing. You will find out that your WebPages don’t have any blocking resources. Everything will seem ok. You may also use WebPagetest tool that helps you to test your website from anywhere in the world. This tool provides a measurement which is called speed index. It measures the time that your WebPages take to response. It also measures how quickly the content was painted. You must compare the measurement before and after you have made the changes. Then you will understand the improvements.

Something More

After all you’ve done there is still something that may hamper the performance of your website. The negative side of inlining the critical CSS is you miss out on caching CSS in the browser because you inlined it in the page. Inlining critical CSS may trouble you if you deal with dynamic pages that change often. There are a lot of saying about inlining critical CSS and asynchronously loading the remaining non-critical CSS. You should read more books and articles on them to get a better idea.

If you are a user of CDN (Content Delivery Network) you should serve your non-critical CSS from the CDN. Then you may serve cached resources directly from the edge. This will improve your website speed. Inlining the CSS may not always work for you well all the time. It’s so important to understand how critical CSS works and how it may help you.

Last of All

No matter how hard you try or how much effort you give you still may have problems. You still may have areas to improve, bugs to fix in your project. I will suggest you to pull request and help contribute to the project on GitHub. If you can optimize the critical rendering path for your website, you may improve a lot more to load your pages quickly. That’s what attracts users mostly. So work hard, try your best and provide a faster experience.

Reference Links:

  1. https://developers.google.com/speed/pagespeed/insights/
  2. https://github.com/addyosmani/critical 
  3. http://addyosmani.com/blog/ 
  4. http://gruntjs.com/ 
  5. http://deanhume.com/Home/BlogPost/automatically-removing-unused-css-using-grunt/6101 
  6. https://github.com/bezoerb/grunt-critical 
  7. http://phantomjs.org/ 
  8. http://www.webpagetest.org/ 
  9. https://sites.google.com/a/webpagetest.org/docs/using-webpagetest/metrics/speed-index 
  10. http://calendar.perfplanet.com/2011/why-inlining-everything-is-not-the-answer/ 
  11. https://medium.com/@drublic/a-counter-statement-putting-the-css-in-the-head-f98103d09ce1 
  12. https://github.com/pocketjoso/penthouse 
  13. https://github.com/filamentgroup/criticalCSS 
  14. http://www.filamentgroup.com/lab/performance-rwd.html 
  15. http://www.smashingmagazine.com/2014/09/08/improving-smashing-magazine-performance-case-study/ 
  16. https://www.udacity.com/course/ud884 
  17. https://developers.google.com/web/fundamentals/performance/critical-rendering-path/ 
Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in coding

About Me:

Szabi Kisded

Hey there, I'm Szabi. At 30 years old, I quit my IT job and started my own business and became a full time WordPress plugin developer, blogger and stay-at-home dad. Here I'm documenting my journey earning an online (semi)passive income. Read more

Sign up for my newsletter and get the YouTube Caption Scraper WordPress plugin for free
(worth 29$)!

All My Plugins In A Bundle:

My AutoBlogging Plugins:

My Online Courses:

A Theme I Recommend:

Featured Posts:

To Top