Optimize Google Font with JavaScript

TABLE OF CONTENTS
A beautiful website also needs a good font set. You can use Google Font to get the Font set you like. However, this more or less affects the loading speed of the website and it also reduces the internal performance score PageSpeed Insights.
There are many articles on how to optimize Google Font using attributes font-display: swap
. But it only fixes the "webfont load" error and does not increase performance score.
In this article, I will show you how to optimize Google Fonts with JavaScript so you can freely choose fonts for your website without worrying about speed anymore.
To choose Font you need to access Google Fonts.
As my example, the Font "Montserrat" has 2 font sizes "400" and "700".
You can also choose many other font styles and import them into a single url.
These are 2 ways to download Google's default Fonts.
<!-- 1. <link> -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
<!-- 2. @import -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap');
</style>
Even though Google Font has added properties font-display: swap
. But when testing performance on PageSpeed Insights, I still get errors related to FCP (First Contentful Paint) and LCP (Largest Contentful Paint).
To fix this problem, I will load Google Font with JavaScript code and place it at the bottom of the page (Footer).
<script>
document.addEventListener("DOMContentLoaded", () => {
const script_font = document.createElement('link');
script_font.href = 'https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap';
script_font.setAttribute('rel', 'stylesheet');
document.body.appendChild(script_font);
});
</script>
At the line script_font.href
Please get the url from the item @import
that Google provides.
After changing this way of loading Fonts, check your website speed to see if it has improved.
Related Articles