Bootstrap + Google PageSpeed Insights 的 Gatsby 优化

Gatsby Optimization With Bootstrap + Google PageSpeed Insights

我正在尝试使用 Google PageSpeed Insights/Lighthouse 优化我的网站速度。我目前的分数大约是 37,但我认为这主要是由于页面的 API 请求量很大(大约 30-40)。 Here's the Google PageSpeed Insights

如何解决避免更改关键请求问题?

盖茨比-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;

为什么要使用 CDN 在 gatsby-browser.js<Helmet> 组件中导入 Boostrap?您正在使用 gatsby-browser 以及每次呈现 <Layout> 时在所有页面中导入这些样式(我猜在您的大多数组件中),因为您的 <Helmet> 放置在 <Layout> 组件中.有点乱。

由于您正在使用 import 'bootstrap/dist/css/bootstrap.min.css';,您的样式将被放置在所有站点中。来自 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.

删除您的 <Helmet> 样式并确保 https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.cssbootstrap/dist/css/bootstrap.min.css 具有相同的样式以避免被清除。你必须尽可能减少外部请求,至少是你项目中易于替换的样式。

通过此删除,您将改进结果请求以及渲染块样式。

您的 PageSpeed Insights 还显示大量未使用 JavaScript(将近 1 秒)。