U Avalos
U Avalos

Reputation: 6798

Wait for CSS to load on a nextjs static site?

I have a nextjs static site. As you can see from the screenshot, the JS loads fast but then it waits for the styled-components to apply the CSS. The CSS is applied after the page loads.

Any ideas how I can either wait for the styled-components CSS to kick in?

static app

UPDATE: ah, I forgot that this is a static app---that means nextjs will pre-render the output of the page, and then load the JS. So it looks like standard techniques to wait for JS to load should apply. HOWEVER...the gotcha is that the static HTML is auto-generated by nextjs, so need a way to do that thru nextjs.

Upvotes: 3

Views: 6334

Answers (1)

Ikechukwu Eze
Ikechukwu Eze

Reputation: 3151

Install Babel-plugin for styled-components => npm i -D babel-plugin-styled-components

Then Create 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 want to use ThemeProvider from styled-components, add the ThemeProvider to pages/_app.js.

This is an example provided by Next.js

Upvotes: 7

Related Questions