Minimizing Google Fonts by Only Loading it for Certain Characters
When it comes to using custom fonts on websites, the de-facto way to do currently is to use the Google Fonts.
Now, most people would add direct URLs to the fonts provided by Google Fonts instead of self-hosting them like so.
<link href="https://fonts.googleapis.com/css2?family=Roboto+Serif" rel="stylesheet" >
This works fine but here’s a scenario. Let’s say you want to use a custom font only for certain characters.
For instance, I want to use the Roboto Serif fonts only for my site title “Amit Merchant”. In such a case, it doesn’t make sense to load the entire font file since we only need a handful of characters for the title.
Google Fonts provides a way to optimize this.
For the scenario I just described, you can append an additional query parameter
text to the font request URL. This allows Google to return a font file that’s optimized for your request. In some cases, this can reduce the size of the font file by up to 90%.
So, if I only want to load the font file for the characters in “Amit Merchant”, here’s how I can do it.
<link href="https://fonts.googleapis.com/css2?family=Roboto+Serif&text=Amit%20Merchant" rel="stylesheet" >
Doing this can effectively reduce the size of the font file by up to 90% and in turn optimize the overall font request!
👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!