I recently made some changes to my website (this). I wasn’t worried about the page performance at first; the goal was to make it work and worry about performance later.
Pagespeed insights
When the initial modifications were live on my website, I checked some pagespeed insights. Here are the results
Mobile
The SEO reported in the initial tests is wrong. The actual value is 100 for both tests. Since the tests are run on a preview URL, Cloudflare pages add the
X-Robots-Tag: noindex
to make it non-indexable
Desktop
Improving the scores
Defer non-critical js
The mobile page was loading a /toggle-theme.js
, which is not immediately required on page load. So I deferred the script loading.
<script is:inline src="/toggle-theme.js" defer></script>
Eliminate render-blocking resources
This site loads two fonts, one for the typography and the other for the code blocks. Preloading the fonts helped solve this issue.
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="preload"
href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible&family=Roboto+Mono&display=optional"
as="style"
onload="
this.onload = null; this.rel = 'stylesheet'
"
/>
<noscript>
<link
href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible&family=Roboto+Mono&display=optional"
rel="stylesheet"
/>
</noscript>
The script loads the font CSS asynchronously and processes them as soon as they load. The onload
is set to null
so that browsers don’t redo any of these steps upon switching the rel
attribute. You can read more about this on web.dev.
Minimizing CLS
The google fonts standard CSS snippet sets the display attribute as swap
. This does not block your page from the font loading, which means that your page is painted first, and when the fonts are loaded, it gets applied. This behaviour caused CLS(Cumulative Layout Shift). The font preloading only caused the CLS to reduce.
The solution was to change the display attribute to optional
. Optional does the following
-
Switches to the fallback font on load
-
If the custom font takes too long to load, it does not switch to the custom font. This will cause your initial page to have a different font, so make sure you set fallback fonts of the same category.
If you’re using tailwind, this is easy to do,
sans: ["Custom Font", ...defaultTheme.fontFamily.sans];
Read more about font display attributes here.
Final scores
Mobile
Desktop
The scores improved, but there’s still some work on mobile regarding FCP. You don’t always need a perfect score on all the metrics, but it feels good when you have them. Apart from solving silly issues, I also improved the user experience on my website.
If you have any pointers or if there’s something I could’ve done better, please let me know.