Critical Path CSS in Laravel

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:

Teylor Feliz
Teylor Feliz

Teylor is a seasoned generalist that enjoys learning new things. He has over 20 years of experience wearing different hats that include software engineer, UX designer, full-stack developer, web designer, data analyst, database administrator, and others. He is the founder of Haketi, a small firm that provides services in design, development, and consulting.

Over the last ten years, he has taught hundreds of students at an undergraduate and graduate levels. He loves teaching and mentoring new designers and developers to navigate the rapid changing field of UX design and engineering.

Articles: 182