Is it necessary to wait for CSS to fully load on a static site built with Next.js?

I am currently working on a Next.js static site. The JavaScript loads quickly, but there seems to be a delay in applying the styled-components CSS as seen in the screenshot. The CSS only kicks in after the page has fully loaded.

Does anyone have any suggestions on how I can make sure that the styled-components CSS is applied without any lag?

UPDATE: I just realized that this is a static application---meaning that nextjs will pre-render the page output first, before loading the JavaScript. This implies that standard techniques for waiting for JS to load should work. However, since the static HTML is automatically generated by nextjs, I need to find a way to do this through nextjs itself.

Answer №1

To get started, install the Babel-plugin for styled-components with the following command:

npm i -D babel-plugin-styled-components

Next, create a new file called pages/_document.js


import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    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()
    }
  }

If you plan to use ThemeProvider from styled-components, remember to add it to your pages/_app.js file.

Check out this example provided by Next.js for more information

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

The @urql/exchange-auth module does not include the token in the header when making requests

I am currently utilizing the urql GraphQL client in my project. However, I have encountered an issue where the authorization token is not automatically added to the header after logging in. In order to set the token in the header, I have to refresh the pag ...

Interact with the :before pseudo element when hovering over an element

Is there a way to manipulate the :before pseudo element when hovering over the main element? My goal is for the pseudo element to change its height when I hover over the main element. This is how my code looks: HTML <div class="object">& ...

Is it possible to modify a scss style in Prestashop?

I have encountered an issue while using a default theme in Prestashop 1.6 that I need assistance with. My goal is to move the navbar up by 25px. I understand that I should make changes to #block_top_menu { padding-top: 25px; } in blocktopmenu.scss, which ...

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

Enhancing game menus for various mobile screen sizes

I've noticed a consistent pattern in the games I download from the Google Play Store - they all have a background image at the menu with clickable buttons. When testing these games on different devices, I found that the backgrounds didn't stretch ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer? Here is the code snippet: <a href="#" class="clickIn" id="1" attrIn="Like"><span style="color ...

Obtain access to global.window.localStorage within getServerSideProps

I have a component that receives props with data and renders the data. In my functionality within the getServerSideProps, I am attempting to retrieve data from localStorage. However, due to window being undefined, I am unable to do so. I have tried using ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Enhancing Your Images with jQuery

Hello When working with jQuery, the following code can be used to darken an image. On the contrary, how would you go about brightening up an image? $(this).hover(function() { $(this).stop().animate({ opacity: 0.5 }, 500); }, function() { $(thi ...

Issue with NextJS callback URL redirecting to another page is not occurring

When attempting to access a /Dashboard page after logging in through Gmail or GitHub on the client side using callbackUrl, I am encountering a 404 error stating that the page could not be found. The project directory structure for the relevant files is as ...

Embedding a video element results in an unexpected increase in height

When I insert an HTML5-Video element into a div, it results in the wrapper having a height larger than the video itself. The wrapper is 7px taller than the actual video source, without any min-height set. Check it out! (Scroll down to the Video) The vide ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

What is the reason behind the exclusion of post categories from Strapi's API?

I have created two content types: post and category. The category has a relationship of many-to-many with the post content type. However, I am unable to retrieve each post's category through the API! The API URL that I am using to fetch all posts ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Changing colors when hovering over different elements

I am struggling to create a hover color change effect that applies to all elements (icon, text, and button) from top to bottom. Currently, the hover effect only changes the color of either the text and icon or the button individually. Below is the code sn ...

What is the best way to utilize useClient in the code of my Next.js project?

I've been attempting to execute the code attached below, but I keep encountering an error stating that a component being imported requires useState and should only be used in a Client Component. However, none of its parent components are marked with " ...

The error message "Unable to access property 'slideHandler' of null in react-slick" is displayed

My current component utilizes two sliders in total (4 in combination) - one for horizontal carousel and the other for vertical, based on screen size. On smaller devices, it works perfectly fine, but on larger screens, it renders initially but crashes when ...

The dropdown menu in Bootstrap is malfunctioning despite the up and down arrow keys working properly

I've been attempting to create a basic dropdown menu using Bootstrap dropdown, and so far, it's been working perfectly in most instances. However, on certain pages, when I click on the three dots that are supposed to activate the dropdown, nothin ...

Responsive Website with Horizontal Scrolling

Is it feasible to develop a website that smoothly scrolls across five panels horizontally while maintaining responsiveness? I've managed to achieve this for a specific viewport size by nesting a div with the five panels extended and using javascript t ...