Open dermyhughes opened 3 months ago
The plan to solve the bug involves preloading the Google font to ensure it is available as soon as possible, thereby reducing the time to the first paint on the homepage. This can be achieved by making changes in both the gatsby-ssr.js
and Layout.tsx
files to preload the font during server-side rendering and client-side rendering, respectively. Additionally, we need to ensure that the font-family in the _defaults.scss
file correctly references the preloaded Google font.
The bug is caused by the delay in loading the Google font, which is currently being fetched only after the client-side JavaScript runs. This delay results in a longer time to the first paint on the homepage. By preloading the font, we can prioritize its loading and reduce this delay.
Add the following code to preload the Google font during server-side rendering:
// gatsby-ssr.js
import React from "react";
export const onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<link
key="google-font-preload"
rel="preload"
href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap"
as="style"
onLoad="this.onload=null;this.rel='stylesheet'"
/>,
<noscript key="google-font-noscript">
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap"
/>
</noscript>,
]);
};
Update the font-family to correctly reference the preloaded Google font:
body {
font-family: 'Permanent Marker', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
Modify the <Helmet>
component to preload the Google font during client-side rendering:
import React from 'react';
import { Helmet } from 'react-helmet';
const Layout = ({ children, site, bodyClass }) => (
<>
<Helmet>
<html lang={site.lang} />
<style type='text/css'>{`${site.codeinjection_styles}`}</style>
<link
rel="preload"
href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap"
as="style"
onLoad="this.onload=null;this.rel='stylesheet'"
/>
<noscript>
<link
href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap"
rel="stylesheet"
/>
</noscript>
<body className={bodyClass} />
</Helmet>
{children}
</>
);
export default Layout;
By implementing the above changes, the Google font will be preloaded during both server-side and client-side rendering, reducing the time to the first paint on the homepage.
Click here to create a Pull Request with the proposed solution
Files used for this task:
The home page takes a second to load fully every time as the first thing a user sees is the large text, that load a google font, which takes a second to load.