vercel / next.js

The React Framework
https://nextjs.org
MIT License
126.4k stars 26.9k forks source link

Font optimization breaks dynamic font loading #20134

Closed kripod closed 3 years ago

kripod commented 3 years ago

Bug report

Font optimization has been enabled in the canary releases of Next.js, by #19758. Since then, Google Fonts stylesheets cannot be injected in runtime with next/head.

Describe the bug

I'm using the gist below for loading Google Fonts on demand:

https://gist.github.com/kripod/52c0f37ad6c4d5e84b4e3a7bc976f50b

Usage example:

<GoogleFontsSheet
  fonts={{
    "Source Sans Pro": [
      { wght: 400 },
      { wght: 400, ital: 1 },
      { wght: 700 },
      { wght: 700, ital: 1 },
    ],
    "Playfair Display": [{ wght: 700 }],
  }}
/>

It generates the following code:

import Head from "next/head";

<Head>
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" />
</Head>

However, when passing user-changeable data to the fonts prop of <GoogleFontsSheet>, the corresponding style sheets refuse to load.

To Reproduce

Please see the instructions above.

Expected behavior

Runtime injection of Google Fonts via <link> elements should be allowed. The optimization shouldn't remove elements which load fonts dynamically.

System information

rishi-raj-jain commented 3 years ago

Is this what you're looking forward to https://codesandbox.io/s/tender-pike-vyybw?file=/pages/index.js ?

The above code does fetch fonts on demand, where in right now it'd change the font after 2 seconds in next/head. [Can be done the same with user input]

kripod commented 3 years ago

Unfortunately, this is still an issue, and Next.js 10.2 has been released with this bug. That’s how dynamic font loading looks now (trying to inject <link> elements on the fly):

Uniform-looking fonts
kripod commented 3 years ago

This seems to have been resolved by #26608.

balazsorban44 commented 2 years ago

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.