Stop Next.js CSS transitions from firing on page load?

Answered
rusty1_rusty1 asked this question 1 year, 4 months ago
rusty1_rusty1 on Jan 26, 2022 · Edited

When my page initially loads, sometimes the CSS transitions fire when the page loads. This is when I'm not intending for those CSS transitions to fire.

How do I stop my Next.js application from firing those CSS transitions on page loads?

Thanks in advance! This is an annoying issue I can't find a solution for!

3 suggested answers
·
1 reply
nick on Jan 30, 2022

I've dealt with this issue before in my Next.js applications, it's possibly due to a chrome bug.

I fixed it by creating a /pages/_document.js and adding a script tag with an empty space.

The /pages/_document.js file would look like this:

import Document, { Html, Head, Main, NextScript } from "next/document"

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html lang="en" translate="no">
        <Head />
        <body>
          <Main />
          <NextScript />
          <script> </script>
        </body>
      </Html>
    )
  }
}

export default MyDocument
1 reply
rusty1_rusty1 on Jan 30, 2022

Thanks!

This solved the problem for me!

moon_man41 on Jan 30, 2022

Try adding a <script>0</script> tag right after the opening <body> element in your application.

0 replies
coderguy on Jan 30, 2022

You can also try telling Next.js to automatically inline CSS so that all the CSS is available to the page when it first renders. That may fix the issues you're experiencing.

To do this, add the property below to your next.config.js file:

module.exports = {
  experimental: {
    optimizeCss: true,
    ...
  },
  ...
}

You'll need to install the Critters NPM package for this to work:

npm install --save critters
0 replies
Answered