DEV Community

Deniz Akşimşek
Deniz Akşimşek

Posted on • Originally published at denizaksimsek.com on

Eleventy — Dynamically Inlining Google Fonts

When you add Google Fonts to your website by copying the link from the fonts.google.com website, you create a request chain. That is, after loading the HTML of your page, the browser then needs to request a bit of CSS from Google, and only then can it start loading the fonts themselves.

A simple solution to this is to copy the CSS returned by Google and paste it into a <style> element in your page. However, I like to change fonts quite frequently, and I’d like to automate this process. This is easy with Eleventy.

A JavaScript data file

We simply fetch the CSS at build time.

// _data/googleFontsStylesheet.js
const fetch = require('node-fetch')
const url = 'the URL in the Google Fonts stylesheet link href'
module.exports = fetch(url).then(res => res.text())
Enter fullscreen mode Exit fullscreen mode

And include it in our base layout.

<style type="text/css">{{googleFontsStylesheet|safe}}</style>
Enter fullscreen mode Exit fullscreen mode

Enjoy your improved Lighthouse scores!

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (1)

Collapse
 
harveyramer profile image
Harvey Ramer

This results in code that loads webfonts beautifully on Mac, but not on Chrome IOS or Windows. I think Google loads OS aware code.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay