Inlining Critical CSS in Your Website
Improve your website's loading speed and user experience by inlining critical CSS. This guide explains how to use PerfBee's Critical CSS feature to optimize your site's performance.
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 easily integrate critical CSS using plugins or directly in their theme files:
- Use the Critical CSS field in plugins like WP Rocket or Perfmatters.
- 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 audit (available in the PerfBee Dashboard under the Performance Boost tab).
- Check the 'Eliminate render-blocking resources' audit. If the audit passes, your critical CSS is correctly implemented.
When to Re-extract Critical CSS
It's crucial to re-extract and update your critical CSS after any major design changes or theme updates to ensure optimal performance. This guarantees the critical CSS accurately reflects the current above-the-fold content.