Load the React chunk CSS dynamically to optimize performance and only when it is necessary

After running an audit, Lighthouse is advising me to "Defer unused CSS" for my React app. Despite implementing code splitting and having separate CSS files for each chunk, the suggestion persists. One particular example highlighted by Lighthouse is the footer chunk. The footer component is lazy loaded using react-lazyload, meaning it will only load when scrolling down the page.

The issue arises as the CSS associated with the footer component is still being loaded into the head of the page even though the component itself is not rendered initially. This is what Lighthouse is flagging as problematic.

Is there a way to delay loading the CSS into the head until the specific component is actually rendered or needed?

Just to provide context, I am operating within a non-ejected Create React App (CRA) environment.

Answer №1

If you want to ensure everything loads smoothly, consider importing the stylesheet directly into the footer component using import './styles.css'

Alternatively, you could experiment with a different approach 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>
        )
    }
};

Answer №2

One approach that I have found to be effective is utilizing lazy-loading.

import { lazy, Suspense } from 'react';

Instead of directly importing your css files, consider placing them into a 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;

Next, lazily load this component as follows:

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

Lastly, utilize Suspense to ensure the css resources are loaded only when necessary:

<Suspense fallback={<></>}>
  <Styling />
</Suspense>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Something seems off with Chrome

I am facing a unique issue that I need help with. Unfortunately, the code is too long to post here but essentially it involves creating a menu for a website. The menu works perfectly and looks great on all browsers except for Chrome. This is unusual as Ch ...

"Expo Securestore is encountering an issue where it is unable to store the user ID and token following authentication

I am currently working on securely storing the userId and token in SecureStore. I have successfully retrieved the token from SecureStore on the next screen, but for some reason, I am unable to see the userId. const doUserLogIn = async() => { try { ...

Issue with jQuery's addClass() function not functioning properly on Internet Explorer versions 8, 9, and possibly others as well

Here is some basic HTML code: <div class="stuff-choice"> <div class="item a"> <label class="signup-checkbox"> <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things"> <strong>A&l ...

Navigating with React: How can I automatically route to the corresponding tab based on the URL?

I've been grappling with this issue for days now - I can't figure out how to automatically navigate to a specific tab when entering its URL. You can check out the code here In the code, I created a tab using Material-UI tabs component. By appen ...

Customize your MUI Select to show the selected value in a different way within the Input field

I have a collection of objects and I am looking to link multiple attributes of the object in MenuItem, but I only want one attribute to be displayed in Select https://i.sstatic.net/kDKLr.png The image above displays "10-xyz" in the select display, when i ...

Optimizing logical expressions in C++

Can I assume in C, C++, JavaScript, or any other modern language that if I have the following code snippet... bool funt1(void) {…} bool funt2(void) {…} if (funt1() && funt2()) {Some code} ...I am guaranteed that both functions will be called, ...

Pinterest Style Card Layout using React-Semantic-UI

Utilizing semantic-ui-react in React, I am working on displaying cards with varying heights based on the amount of text. I am aiming for a pinterest style layout where each card's height adjusts according to the content it contains. .... <Card.Co ...

An issue occurred while recognizing the create-react-app, despite being duly installed

After successfully installing create-react-app, I encountered an issue when attempting to create my own app. A message stating 'create-react-app' is not recognized as an internal or external command appeared. You can see the exact error message ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

Troubleshooting Problems with Refreshing Keycloak in React Router

I recently embarked on my journey with stack after stumbling upon a tutorial that caught my interest: However, I've encountered an issue where every time I navigate to a new page using the menu, the web app refreshes and loads keycloak again. While I ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

When the width of the element is set to 100vw, it disrupts the

I'm attempting to expand a sticky element to fit the size of the screen. Here is the HTML code I am using: .large { height: 200vw; width: 200vw; } .header { left: 0; top: 0; color:white; position: sticky; width: 100px; height: 10 ...

troubles with spacing and layout in react native's flexbox

Struggling to create some breathing room by adding margin to the grid without causing it to wrap and start a new row? Sounds like setting specific values isn't an option due to responsiveness constraints. Here's a snippet showing the grid before ...

Implementing authentication fallback during re-login when a session expires in a web application built with React, Node.js, and Mariadb database

Greetings everyone, this is my debut post here so kindly bear with me :D. Currently, I am in the process of developing a social app where I am incorporating a fallback mechanism for situations when my database goes offline. Within my Login.jsx component, I ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Having trouble connecting to the 'Post' collection in Prisma MongoDB, but the 'User' collection is running smoothly

I am currently developing a Next.js 13 application utilizing Prisma as the ORM and MongoDB as the database. In my Prisma schema, I have defined two models: 'User' and 'Post'. While the 'User' model is functioning correctly, I ...

Is it necessary for the useSWR hook in swr to send an HTTP request for revalidation each time the data is accessed, even if cached data already exists?

As I delved into the SWR react hook documentation and the Stale-While-Revalidate methodology, it became clear that SWR utilizes cached data as a temporary placeholder to quickly display results to users. (While SWR has numerous benefits, this aspect stood ...

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

Optimizing the placement of elements within a grid

I am working on implementing a header for my application with specific alignment requirements. I need the left item (A) to be aligned to the left side of the header, the second item (B) to be in the center, and the third item to be aligned to the right. A ...