Gatsby - change over-the-fold initial HTML

Viewed 704

I'm building landing pages with the amazing Gatsby framework (version 2.16.1).

Everything would have worked perfectly, except that I can't find a way to make changes to the HTML that's being loaded before any script is loaded (the 'over-the-fold' initial HTML).

For example, if I change the HTML's background color in Gatsby - Users can wait up to 5 seconds since the 'over-the-fold' initial HTML is displayed, until the background color is applied.

I know about gatsby-browser.js and the ability to make global CSS files, but that's no use for me as I use a different color or background-picture for each landing page.

My question is: Can I affect the first loaded HTML (differently for each Gatsby page) in Gatsby or React?

Illustration: I color the background color as yellow, but the flow is like this -

HTML is first displayed (background=while) -->
3-5 seconds later -->
all scripts are loaded, and background changes to yellow
2 Answers

@ksav answered the question in a comment to the question! Thank you!

The answer is using a function called onRenderBody under the gatsby-ssr.js file, as explained in the article that was mentioned: https://www.gatsbyjs.org/docs/custom-html/

exports.onRenderBody = ({setBodyAttributes,pathname,}) => {
  // Differentiate between the landing pages here
  switch(pathname) {
    case 'landing_page_a':
    case 'landing_page_b':
  }

  // Affect the HTML that gets loaded before React here
  setBodyAttributes({
    style: {
      backgroundColor: 'red',
    },
  });
}

The funny thing is, that I've already bumped into this article before, but didn't think it was relevant because it talked about server-side-rendering, and I know that Gatsby is server-less. After @ksav 's comment, I re-read it, and understood that the server-side-rendering happens during Gatsby's build process, and not during run-time (i.e. when the user enters the landing pages).

Can I affect the first loaded HTML (differently for each Gatsby page) in Gatsby or React?

Yes, you can directly in the JSX React code. Google has documentation how you can optimize CSS delivery so your above-the-fold content is always styled correctly. It comes down to using inline CSS for all your components above the fold. With inline CSS your HTML elements are always styled when they are loaded because the styling is part of the HTML code.

See the React documentation for how to handle inline styles in React.

An example from the Gatsby tutorial:

src/pages/index.js

import React from "react"
export default () => (

  {/* inline CSS */}
  <div style={{ margin: `3rem auto`, maxWidth: 600 }}> 

    <h1>Hi! I'm building a fake Gatsby site as part of a tutorial!</h1>
  </div>
)
Related