Search code examples
optimizationgatsbypagespeedgoogle-pagespeedlighthouse

Gatsby Optimization With Bootstrap + Google PageSpeed Insights


I'm trying to optimize my site in speed using Google PageSpeed Insights/Lighthouse. My current score is around 37, but I think that is mainly due to the large amount of API requests the page does (Around 30-40). Here's the Google PageSpeed Insights

How do I fix this Avoid Changing critical requests issue?

enter image description here

gatsby-browser.js

// Imports: Dependencies
import 'bootstrap/dist/css/bootstrap.min.css';

Layout.js

// Layout
const Layout = ({ children }) => {
  return (
    <div className="layout">
      <Helmet>
        <link
          rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous"
        />

        <meta charSet="utf-8" />
        <title>COVID-19</title>
        <html lang={'en'} />
        <link rel="canonical" href="https://orangecountycovid19.com" />
        <meta name="description" content={'Orange County, CA COVID-19 Tracker'} />
      </Helmet>

      <div>{children}</div>
    </div>
  );
};

// Exports
export default Layout;

Solution

  • Why are you importing Boostrap in your gatsby-browser.js as well as in your <Helmet> component using a CDN? You are importing those styles in all your pages with gatsby-browser plus each time you render <Layout> (in most of your components I guess) since your <Helmet> is placed in <Layout> component. It's kinda messy.

    Since you are using import 'bootstrap/dist/css/bootstrap.min.css'; your styles will be placed in all the site. From Gatsby documentation:

    1. Create a global CSS file as src/styles/global.css and paste the following into the file:
    2. Import the global CSS file in the gatsby-browser.js file such as the following: Note: You can also make use of require('./src/styles/global.css') to import the global CSS file in your gatsby-browser.js file.
    3. Run gatsby-develop to observe the global styling being applied across your site. Note: This approach is not the best fit if you are using CSS-in-JS for styling your site, in which case a layout page with all the shared components should be used. This is covered in the next recipe.

    Remove your <Helmet> styles and ensure that https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css has the same styles than bootstrap/dist/css/bootstrap.min.css to avoid a purge. You must minimize as much as possible outside requests, at least of styles that are easy to replace in your project.

    With this removal, you will improve outcome request as well as render-block styles.

    Your PageSpeed Insights also show a humongous amount of unused JavaScript (almost 1 second).