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.
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>
)
}
};
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With