等待 CSS 加载到 nextjs 静态站点上?

U A*_*los 1 css styled-components next.js

我有一个 nextjs 静态站点。正如您从屏幕截图中看到的,JS 加载速度很快,但随后会等待样式组件应用 CSS。CSS在页面加载应用。

我有什么想法可以等待样式组件 CSS 启动吗?

静态应用

更新:啊,我忘了这是一个静态应用程序---这意味着nextjs会预渲染页面的输出,然后加载JS。所以看起来应该应用等待 JS 加载的标准技术。然而……问题是静态 HTML 是由 nextjs 自动生成的,所以需要一种方法通过 nextjs 来做到这一点。

Ike*_*Eze 5

为 styled-components 安装 Babel-plugin => npm i -D babel-plugin-styled-components

然后创建 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()
    }
  }

Run Code Online (Sandbox Code Playgroud)

如果你想从 styled-components 中使用 ThemeProvider,请将 ThemeProvider 添加到 pages/_app.js。

这是 Next.js 提供的示例