A Smart Way to Optimize Google Fonts

ยท 1 minutes read
Frans Allen

This site is just a static site hosted on my small server, but has the capability for on-demand Google Fonts Optimization. This feature will convert Google Fonts URL (fonts.gstatic.com) to local font links and create a new <style/> element with the data from the Google Fonts CSS code (fonts.googleapis.com), replacing the existing <link/> element.

By downloading the data and embedding it as an inline style, I can reduce DNS lookups and improve performance for this site.

You can check the source code to see what this functionality looks like if you want.


Basically, if I put code like this

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600;700;900&display=swap" />

in the <head/>, it will automatically be converted into an inline style code.

This hack provides me with a smart way to load Google Fonts on the same domain as the page. Fast and minimal DNS lookup, awesome!