【问题标题】:Wait for CSS to load on a nextjs static site?等待 CSS 在 nextjs 静态站点上加载?
【发布时间】:2020-08-06 06:03:19
【问题描述】:

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

有什么想法可以等待 styled-components CSS 启动吗?

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

【问题讨论】:

    标签: css next.js styled-components


    【解决方案1】:

    为 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()
        }
      }
    
    

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

    This is an example provided by Next.js

    【讨论】:

    • 太棒了!以前见过这个,但因为它是一个静态应用程序,所以认为它不适用。但这解决了它:-)
    • 这对我来说非常有效。很长一段时间以来,我一直在寻找解决方案。谢谢!
    猜你喜欢
    • 2022-07-05
    • 1970-01-01
    • 2020-08-29
    • 2012-06-17
    • 2021-09-28
    • 2023-01-26
    • 2019-11-07
    • 2021-02-05
    • 2014-12-18
    相关资源
    最近更新 更多