Asynchronous Google Fonts

Last updated:

Limit the render blocking effect of Google Fonts

Improve page speed and user experience by reconfiguring Google Fonts to load asynchronously in the background.


The normal CSS reference to add one or more Google fonts - for example the regular and bold variants of Roboto - looks like this:

HTML
<!-- other <head> stuff -->

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap">

</head>

To load the same resource in the background while the page continues loading, use this simple asynchronous CSS technique with the media attribute, plus some additions to manage loading priority and include a no-JS fallback:

HTML
<!-- other <head> stuff -->

 <!-- connect to domain of font files -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="https://fonts.gstatic.com" crossorigin> <!-- (fallback when preconnect isn't supported) -->

 <!-- optionally increase loading priority -->
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" as="style">

 <!-- load font CSS in the background then apply when loaded -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" media="(max-width:1px)" onload="this.onload=null;this.removeAttribute('media');">

<!-- conventional CSS reference for no-JS fallback -->
<noscript>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap">
</noscript>

</head>

Of the 4 parts included above, 3 are optional depending on the context:

Without JavaScript

Placing the CSS reference at the bottom of the HTML has a similar effect, but the technique above starts the loading process sooner, potentially reducing the potential flash of unstyled text.


Questions? Need help?

Email Me

Learn more about maximizing website loading speed:

Complete Guide