NextJS Core Web Vitals - remove render blocking CSS (2024)

Remove render blocking CSS in NextJS

CSS is render blocking. This means that a browser will not start rendering when it finds CSS in the head of the page until all that CSS is parsed. If the browser is required to download one or more external CSS files that might take up precious time. In this article I will show you how to remove those render blocking CSS files in your NextJS app to speed up rendering. This will improve your paint metrics (First Contentful Paint and Largest Contentful Paint)

By default NextJS will create 2 stylesheets for a page. The first is the global stylesheet and the second on a page specific stylesheet. How much time will that cost us? That depends on a lot of factors like the visitors device, the network speed, the network connection protocol, the distance to the server, the size of the stylesheet etc. On average, for all my clients, across all devices I have found this takes about 200ms. On the NextJS website downloading those 2 stylesheets will take 600ms on a fast 3g connection. This will delay all the paint metrics by 600ms. Time to take action and remove these render blocking stylesheets!

NextJS Core Web Vitals - remove render blocking CSS (1)

Option 1: Generate Critical CSS

The first and fastest option is to generate Critical CSS. Critical CSS is a collection of CSS rules that are needed to render the visible part of the page. Those rules are placed inline in the HEAD of the page. Then, in parallel, the original CSS files are downloaded while the browser will continue to render. Once the original CSS files are downloaded they are injected into the page.

Critical CSS is now available in NextJS as an experimental feature. Generating Critical CSS in NextJS is extremely simple. Just add experimental: { optimizeCss: true } to your next.config.js and add install [email protected] as a dependency in your project.

const nextConfig = { reactStrictMode: true, experimental: { optimizeCss: true }}

Option 2: inline CSS in the HEAD of the page.

If you do not want to enable experimental features in your NextJS app to improve the Core Web Vitals you could consider inlining your CSS. You will need to create a custom head section and reference this in your _document.tsx.

The downside to this method is that the inline CSS will probably be larger then with the first method. However if you keep your stylesheets clean and effective this method will most probably improve the Core Web Vitals for your NextJS app significantly!

import { Html, Head, Main, NextScript } from "next/document";import { readFileSync } from "fs";import { join } from "path";class InlineStylesHead extends Head { getCssLinks: Head["getCssLinks"] = ({ allFiles }) => { const { assetPrefix } = this.context; if (!allFiles || allFiles.length === 0) return null; return allFiles .filter((file: any) => /\.css$/.test(file)) .map((file: any) => ( <style key={file} nonce={this.props.nonce} data-href={`${assetPrefix}/_next/${file}`} dangerouslySetInnerHTML={{ __html: readFileSync(join(process.cwd(), ".next", file), "utf-8"), }} /> )); };}export default function Document() { return ( <Html> <InlineStylesHead /> <body> <Main /> <NextScript /> </body> </Html> );} 

Option 3: Styled Components

Styled Components is a CSS-in-JS tool that lets you write CSS in JavaScript files. This has many advantages. For example, you can repeat class names, easily remove unused CSS code, and manage code more easily compared to traditional CSS files. As for the Core Web Vitals it will mean you will only inject the styles that are needed on that page. Pretty neat right?

As of NextJS version 12.1 it is easier then ever to use styled components in your NextJS app. Add compiler:{styledComponents: true} to your next.config.js, install styled-components (yarn add styled-components and when it’s done installing, run yarn add -D @types/styled-components ), update the file _document.js to support server side rendering for styled components and you are good to go!

const nextConfig = { reactStrictMode: true, compiler: { styledComponents: true, }}
import Document, { DocumentContext } from "next/document";import { ServerStyleSheet } from "styled-components";export default class MyDocument extends Document { static async getInitialProps(ctx: DocumentContext) { const sheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), }; } finally { sheet.seal(); } }}
NextJS Core Web Vitals - remove render blocking CSS (2024)

FAQs

How to fix eliminate render blocking resources in CSS? ›

How do you eliminate render-blocking resources?
  1. Inline critical CSS. Inclining critical CSS simply refers to inserting the CSS code directly into the HTML file — rather than loading it separately. ...
  2. Use media queries to load non-critical CSS (conditional CSS) This is taking on from inlining critical CSS. ...
  3. Minify your CSS.

What is a render blocking request? ›

“Render blocking resources” refers to web page resources, such as CSS and JavaScript files. These resources can block web page rendering if certain conditions are met: If the <script> tag is in the <head> of the HTML document AND does not have a defer or async attribute.

Why is CSS blocking in nature? ›

By default, CSS is treated as a render blocking resource, which means that the browser won't render any processed content until the CSSOM is constructed. Make sure to keep your CSS lean, deliver it as quickly as possible, and use media types and queries to unblock rendering.

How does eliminating render blocking resources affect page performance? ›

These resources delay the First Paint - the time at which your browser renders something (i.e., background colours, borders, text or images) for the first time. Eliminating render-blocking resources can help your page load significantly faster and improve the website experience for your visitors.

How to identify your render blocking resources? ›

PageSpeed Insights & Lighthouse

Simply test a URL in either tool, navigate to “Eliminate render-blocking resources” under “Diagnostics,” and expand the content to see a list of first-party and third-party resources blocking the first paint of your page.

Is CSS render blocking or parser blocking? ›

CSS is render-blocking by default.

A parser-blocking resource blocks rendering as well, but in addition it prevents the browser from continuing to parse the HTML and processing other resources in the page.

How to defer CSS files? ›

Defer Media

css or mobile. css and link this file in the head of your HTML. Then use the defer attribute in the @media rule to tell the browser to load the responsive. css file when the page is loaded.

How to eliminate render blocking JavaScript and CSS on WordPress? ›

How to eliminate render-blocking resources in WordPress
  1. Optimize CSS loading. One way to eliminate render-blocking resources is to optimize your website's CSS loading. ...
  2. Defer non-essential JavaScript. ...
  3. Defer off-screen images. ...
  4. Manually remove render-blocking JavaScript. ...
  5. Apply async or defer attributes with a plugin.
Apr 19, 2024

Are inline scripts render blocking? ›

Inline JavaScript also blocks rendering until execution is complete. You can stop <script> tags from blocking rendering by placing them directly before the closing </body> tag.

How do I fix CSS problems? ›

CSS has a similar story — you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. The W3C has a CSS Validator available too, for this purpose.

What is a good CSS file size? ›

How big should a CSS file be? ​ There's no single number, but I would say that less than 20 kilobytes is very good and I wouldn't worry until a CSS file reaches 50 to 100 kilobytes.

Why is embedded CSS bad? ›

Inline CSS can impact performance negatively as each HTML file must carry its styling information. This redundancy increases page load times, especially for larger websites.

How to solve render blocking in CSS? ›

To tackle render-blocking resources, prioritize above-the-fold content, defer non-essential JavaScript, use "async" for non-impactful scripts, minimize and compress CSS/JavaScript, leverage browser caching, and utilize Content Delivery Networks (CDNs).

How to eliminate render blocking resources in NextJS? ›

Add compiler:{styledComponents: true} to your next. config. js, install styled-components (yarn add styled-components and when it's done installing, run yarn add -D @types/styled-components ), update the file _document. js to support server side rendering for styled components and you are good to go!

Are font files render blocking? ›

Web fonts don't block rendering of the page, but they can block rendering of the text itself. How text renders before fonts are loaded is specified by the font-display CSS property.

How do I fix render blocking JavaScript and CSS in WordPress? ›

How to eliminate render-blocking resources in WordPress
  1. Optimize CSS loading. One way to eliminate render-blocking resources is to optimize your website's CSS loading. ...
  2. Defer non-essential JavaScript. ...
  3. Defer off-screen images. ...
  4. Manually remove render-blocking JavaScript. ...
  5. Apply async or defer attributes with a plugin.
Apr 19, 2024

How to fix content using CSS? ›

To make text fixed, you can use the CSS position property with a value of fixed . This will position the element relative to the viewport, meaning that it will not move even if the user scrolls down the page.

How to eliminate render blocking resources in Elementor? ›

To optimize Elementor-generated CSS, and avoid render-blocking issues, you can use plugins like WP Rocket or Autoptimize to minify and combine CSS files. You can inline critical CSS, use asynchronous or deferred loading of CSS files, and remove unused CSS and JavaScript.

Top Articles
Writing an Option: Definition, Put and Call Examples
What are Holiday Home Occupancy Restrictions? - Holiday Cottage Mortgages
Mybranch Becu
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
My Arkansas Copa
Thor Majestic 23A Floor Plan
Ets Lake Fork Fishing Report
Myexperience Login Northwell
Practical Magic 123Movies
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Kristine Leahy Spouse
Slapstick Sound Effect Crossword
Directions To Lubbock
Mndot Road Closures
Nichole Monskey
Simple Steamed Purple Sweet Potatoes
How to watch free movies online
OpenXR support for IL-2 and DCS for Windows Mixed Reality VR headsets
House Party 2023 Showtimes Near Marcus North Shore Cinema
Becu Turbotax Discount Code
Panorama Charter Portal
Baywatch 2017 123Movies
Dirt Removal in Burnet, TX ~ Instant Upfront Pricing
Huntersville Town Billboards
Katie Sigmond Hot Pics
2013 Ford Fusion Serpentine Belt Diagram
Plaza Bonita Sycuan Bus Schedule
Naval Academy Baseball Roster
Apartments / Housing For Rent near Lake Placid, FL - craigslist
Silky Jet Water Flosser
Jcp Meevo Com
Breckiehill Shower Cucumber
Watson 853 White Oval
Cona Physical Therapy
Unreasonable Zen Riddle Crossword
Vivification Harry Potter
Southtown 101 Menu
Mrstryst
Mumu Player Pokemon Go
Wasmo Link Telegram
Kattis-Solutions
Bee And Willow Bar Cart
Elizaveta Viktorovna Bout
Mcgiftcardmall.con
Dr Adj Redist Cadv Prin Amex Charge
Craigslist Com St Cloud Mn
2013 Honda Odyssey Serpentine Belt Diagram
French Linen krijtverf van Annie Sloan
2487872771
2000 Fortnite Symbols
Convert Celsius to Kelvin
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 5864

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.