Next.js: CSS in header

Created on 26 Oct 2016  路  4Comments  路  Source: vercel/next.js

Hello,

I'm trying to include a css resource using the Head component (it's a large css file, so I don't want to use glamor)

<Head>
  <meta charSet='utf-8'/>
  <meta name='viewport' content='initial-scale=1.0, width=device-width'/>
  <link rel="stylesheet" href="/static/css/application.css"/>
  <script defer src="/static/js/application.js"></script>
</Head>

Unfortunately by doing so, when I navigate to another page, the css gets unloaded and then loaded again causing the UI to kinda "flicker".

What's the NextJS way to deal with that use case?

Thank you.

bug

Most helpful comment

We do, it's on the ReadMe here: https://github.com/zeit/next.js#custom-document

All 4 comments

It seems that the flicker is a bug. It shouldn't happen :(

I solved (probably?) the flicker bug by this method:

In your server side code:

api.get('/style', (req, res) => {
  res.send(`
    body {
      background: #eee;
      margin: 0;
    }
  `.replace(/\s{2,}/g, ''))
})

and in every of your pages:

static async getInitialProps ({ req }) {
  const isServer = !!req
  const host = isServer ? req.headers.host : location.origin
  const stylesheet = await (await fetch(host + '/api/style')).text()
  return {
    isServer,
    stylesheet,
  }
}

render () {
  return (
    <div>
      <Head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
        <style dangerouslySetInnerHTML={{ __html: this.props.stylesheet }} />
      </Head>
    </div>
  )
}

Maybe it's still flickering, but around 0ms so your eyes won't see that, since the head element is still being updated every page transition.

really?? On every page?? We don't have a way to customize the html Next uses?

We do, it's on the ReadMe here: https://github.com/zeit/next.js#custom-document

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olifante picture olifante  路  3Comments

jesselee34 picture jesselee34  路  3Comments

knipferrc picture knipferrc  路  3Comments

havefive picture havefive  路  3Comments

kenji4569 picture kenji4569  路  3Comments