As we are moving to Progressive Web Apps and pushing for more performance on the web, it is important to show a fast page that it is styled quickly and avoids CSS files blocking the rendering until they are finished downloading. Thus, instead of downloading all the CSS files required by the page on the page load, we can download only the most critical CSS needed by the content located above the fold.

There are a lot of tools to identify the Critical Path CSS. However, I needed a way to include one CSS file generated by Sass on the header of the page, without having to manually update the CSS on the head each time the content of the file changes.

After identifying the Critical Path CSS, you can create a “critical-path.sass” that will generate a “critical-path.css” on the “public/css” directory in Laravel. Then, it is important to embed the content of the file by using the file_get_contents() function in the head of your template.

 @php
   echo file_get_contents(public_path('css/critical-path.css'));
 @endphp

That’s it! Now, when you make changes to the critical-path.sass and compile it, the CSS will be updated in the head of the page without having to do it manually. This approach should work well for small to medium projects. But, for very large projects, you probably would like to just include the CSS directly without having to use the file_get_contents function. Nevertheless, this works great for developing the application, because it does something automatically without having to interference each time the CSS changes.

More Information about CSS Critical Path:

«
»