Inlining Critical CSS in Your Website
Improve your website's loading speed and user experience by inlining critical CSS. This guide explains how to add the critical CSS you extract with PerfBee to your site.
Category: Critical CSS
What is Critical CSS?
Critical CSS refers to the CSS necessary to render the above-the-fold content of your webpage. By inlining this CSS, you eliminate render-blocking resources, allowing the browser to display content to the user faster.
The Standard Inlining Pattern
The standard method involves three steps:
- Inline Critical CSS: Paste the extracted critical CSS into a
<style>tag within the<head>of your HTML document. Use anidattribute to make it easier to find later:<style id='critical-css'> ... </style>. - Load Full CSS Asynchronously: Replace the link to your full CSS file with a preload tag:
<link rel='preload' href='styles.css' as='style' onload="this.onload=null;this.rel='stylesheet'">. This loads the full CSS in the background. - Provide a Fallback: Add a
<noscript>tag as a fallback for browsers with JavaScript disabled:<noscript><link rel='stylesheet' href='styles.css'></noscript>.
Implementation Instructions
Here's how to implement critical CSS for different platforms:
Plain HTML
- Use PerfBee's Critical CSS feature to extract the critical CSS for a specific page.
- Follow the standard inlining pattern described above.
WordPress
WordPress users can integrate critical CSS using plugins or directly in their theme files:
- Paste the CSS into the critical CSS field of your optimization plugin, if it has one.
- Alternatively, add the code to your child theme's
functions.phpfile.
Next.js / React
For Next.js and React applications:
- In your layout file (e.g.,
app/layout.tsx), usedangerouslySetInnerHTMLto insert the<style>tag with the critical CSS. - Implement the async loading of your full CSS using the preload pattern.
Testing Your Implementation
After implementing critical CSS, test your changes using:
- Lighthouse: Run a Lighthouse test of your site in the PerfBee Dashboard: open Performance Boost in the sidebar.
- Check whether your stylesheets still show up as render-blocking resources in the report. If they no longer do, your full CSS loads without blocking the first render.
When to Re-extract Critical CSS
Re-extract and update your critical CSS after any major design changes or theme updates. This keeps the critical CSS in step with the current above-the-fold content.