Hello World. We are WEB cult. We make a note for web developers.

How to solve CSS loading delay with Gatsby

Written or Updated on August 03, 2022 🖋️

CSS loading delay

When I access the page made with Gatsby, HTML shows up naked and CSS is loaded after a second.

It’s not a big problem but it doesn’t look nice. And why is this happening in the first place?

I found some same issues on Gatsby git repository and some people seem still having the problem.

screen shot

・Gatsby: v3.2.1
・Styled components: v5.3

Potential causes and solutions

There are two potential causes for this problem but those are basically the same thing, which is that CSS is not included when Gatsby does SSR (server side rendering).

1. Proper plugins are not installed

This is an easy mistake. You didn’t install necessary plugins. for instance, styled-components requires the following two package installs.

  • ・styled-components
  • ・babel-plugin-styled-components

But when you want to use styled-components with Gatsby, you need to install gatsby-plugin-styled-component as well and set it on gatsby-config.js

npm install --save gatsby-plugin-styled-component

or

yarn add gatsby-plugin-styled-component
// gatsby-config.js

module.exports = {
  plugins: [
    `gatsby-plugin-styled-components`,
  ]
}

This plugin helps Gatsby to handle styled components on SSR.

2. Gatsby doesn’t know CSS files when it runs SSR

This may be the thing, If you are setting CSS reseter or gloabal CSS on gatsby-browser.js.

// gatsby-browser.js

import { CSSReset } from ''
import { GlobalCSS } from ''

export const wrapPageElement = ({ element }) => {
  return (
    <>
      <CSSReset />
      <GlobalCSS />
      {element}
    </>
  )
}

There is nothing wrong with this but Gatsby browser API only works on the browser.
Each page is generated by SSR but these CSS will not be included because Gatsby doesn’t know about it at the time of SSR.

After that, when the page is loaded on the browser, Gatsby browser API finally runs and CSS arrives. That’s why CSS loading delay happens.

The solution is pretty easy. You should write the same code on gatsby-ssr.js which is setting for Gatsby server rendering API.

// gatsby-ssr.js

import { CSSReset } from ''
import { GlobalCSS } from ''

export const wrapPageElement = ({ element }) => {
  return (
    <>
      <CSSReset />
      <GlobalCSS />
      {element}
    </>
  )
}

Now CSS will be included when Gatsby does server side rendering. So weird loading delay won’t happen anymore!