Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load React chunk CSS only when it's needed

Lighthouse is telling me to "Defer unused CSS" for my React app when I've run an audit. I have implemented code splitting so I have a bunch of chunks that all include their own bits of CSS.

However, I still get this suggestion from Lighthouse and an example is for my footer chunk. My footer is lazy loaded using react-lazyload so will only be rendered when you scroll down the page.

The problem is that even though the footer component isn't rendered initially, it's CSS is still loaded into the head of the page which is what Lighthouse is complaining about.

Is there a way I can only have the CSS loaded into the head once the component actually renders/is needed?

For context, I am working with a non-ejected CRA.

like image 968
Andy Furniss Avatar asked Oct 11 '25 11:10

Andy Furniss


2 Answers

You should be okay if you just load stylesheet from within the footer component, using import './styles.css'

But Maybe you can also try something like this?

import * as React from 'react';

export default class MainPage extends React.Component{

    render(){
        return (
            <div>
                <link rel="stylesheet" type="text/css" href="./style.css" />
                <Footer/>
            </div>
        )
    }
};
like image 55
AlexZvl Avatar answered Oct 14 '25 02:10

AlexZvl


The solution I found useful is to use lazy-loading.

import { lazy, Suspense } from 'react';

Then instead of importing your css files directly, you need to put them into separate component:

import React from ‘react’;
import ‘/path/to/your/example.css’;
import ‘/path/to/your/other/example.css’;
const StylingComponent = ({ children }) => <>{children}</>;
export default StylingComponent;

and then lazy-load this component like that:

const Styling = lazy(() => import('/path/to/your/StylingComponent'));

Then use Suspense to load your css only when needed:

<Suspense fallback={<></>}>
  <Styling />
</Suspense>
like image 33
Piotr Kowalski Avatar answered Oct 14 '25 01:10

Piotr Kowalski