Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby puts all css in head

Tags:

css

gatsby

I am wondering why Gatsby includes not used css in the head tag of each html page.

I created a new project

gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default

I added a css module styled component

.container {
    margin: 3rem auto;
    max-width: 600px;
    border: dot-dot-dash;
}

import React from "react"
import containerStyles from "./test.module.css"

const TestContainer = ({ children }) => (
    <section className={containerStyles.container}>{children}</section>
)

export default TestContainer;

Finally I used the TestContainer in the 404 page and I though that only the resulting 404.html page will include the .container style in the head, but the index.html and the page-2.html includes the styles as well.

My Project contains a lot of css and the index.html is almost twice as big because it include all the css from the whole application.

Am I doing something wrong or is there a reason for doing this ?

like image 841
Simon Ludwig Avatar asked Jan 29 '20 21:01

Simon Ludwig


1 Answers

Gatsby uses webpack and at some point the default behaviour was to code split CSS (i.e. only load the CSS modules when required).

This was causing some undesired behaviour for some users, so the webpack config is now set to only create one CSS file.

Read more about the issue here: https://github.com/gatsbyjs/gatsby/issues/11072 https://github.com/gatsbyjs/gatsby/commit/7058a256d2dcfab91259bdf00e811375737414e7

I've done a quick test with gatsby-plugin-split-css and it appears to give you the desired behaviour. However, I would use caution as you may end up experiencing the issues noted in the links above.

If your concern is that the large style block is loading on every page, then I'd encourage you to open the Network and Elements tabs on your browser DevTools. You will notice that the style block is only loaded once, and when you navigate between pages using Gatsby's <Link>, only the content that needs to be removed/added is updated.

So if your site visitors are landing on index.html first and clicking on a <Link/> to page-2.html, it will make no difference in load time when they click through as the <style> tag persists in the <head> when they click through. If however, they are likely to go to page-2.html directly from an external site, then maybe I could understand the need to code split if the CSS on your index.html page is really long.

like image 144
epsilon42 Avatar answered Oct 24 '22 04:10

epsilon42