The problem
When I access the page made with Gatsby, HTML shows up naked and CSS is loaded after a few seconds.
It’s not a big problem but it doesn’t look nice.
More than that, why is this happening?
I found some same issues on Gatsby git repository and some people seem still having the problem.
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.
Usually, 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!