How to preload Google fonts using Google API

I recently went through the performance issues I had in lighthouse or Google pagespeed. One of those was that I did not preload Google fonts which I use on my site. In order to preload you need a link element with rel="preload". An example of how I preload Google fonts from the google API can be seen below:

<link rel="preload" as="style" type="text/css" 
      href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400&display=swap" />

In the above we define the link relation as preload, using the as attribute we tell that it is a style once it is loaded and that the type is text/css. One thing to keep in mind here is that it does not say "stylesheet" in the “as” attribute like it does on a normal stylesheet link tag, it only says "style". Another is that you can easily mistake this file for being a font file but it is not, it is a CSS file.

The above is what you need in order to preload the CSS, now for loading it you can do the following:

<link rel="stylesheet" type="text/css" 
      href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400&display=swap" />

Keep in mind that these should not be right next to one another or it will defeat the purpose. I have put the preload in the head of my page and the actual stylesheet at the bottom of the body. This way the browser loads the font after the user has been presented with the page.

I hope you found this helpful, let me know in the comments if you did :)