Have you ever seen the error above in the PageSpeed Insights tool as a result of loading web fonts? In this brief tutorial I am going to show you how to load your web fonts asynchronously to avoid this issue. If you are not familiar with CSS and web fonts, check out our CSS3 for Web Designers and Developers course where we cover CSS3 topics, including web fonts.
This causes the browser to fetch the resource prior to the rendering of the page. This is because the browser is programmed to fetch and parse all CSS resources that are defined using @import or the <link rel="stylesheet"> tag. To avoid this, we can load our web fonts asynchronously. While that might sound difficult, it’s not, thanks to TypeKit’s Web Font Loader open-source project.
A big thank you to the TypeKit team that has provided the Web Font Loader project. I am going to use Google’s Font API in my examples. If you are loading fonts from another source, such as TypeKit or FontDeck, check out the documentation for Web Font Loader on GitHub.
If you want to learn more about Node.js and npm, check out our Node.js Software Development Training course. It’s a 2-day course where you learn the basics of Node.js, using npm for dependency management, accessing the file system, and even running an HTTP server using Express.
Notice that I am using the --save flag so that the webfontloader dependency will be saved into my project’s package.json file.
Within the enty.vendor array I have included the webfontloader dependency.
I defined the webfontloader alias within the resolve.alias object.
In this tutorial I am going to use TypeScript. You can ignore the typings in my code examples and skip this step on installing the TypeScript definitions if you are using vanilla JS.
Let’s break down this command, as it is a bit long and potentially confusing. The typings install portion is pretty simple; we’re telling the typings command to run the install command. Then we provide the location. We are instructing typings to use the source dt and the package webfontloader. The source of dt stands for DefinitelyTyped, which is a publicly available repository of TypeScript declaration files. The source of the webfontloader declaration file can be found on GitHub in the DefinitelyTyped repository. Finally, we specify the --global and --save flags. The --global flag instructs typings to install and persist the declaration file as a global definition. And the --save flag instructs typings to save the dependency to the typings.json file.
Next, create a configuration object for WebFont. This is where you will use your own configuration based on the web fonts in your application or on your website. I am going to use Google’s Open Sans and Roboto fonts.