Google Material Icons and Symbols loading issue

481 views Asked by At

Im working on a multiple react projects and we used google icons there, but facing some loading issue at first load.

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />

I use this to import the icons.

<span className="material-icons">pie_chart</span>

This is the way I use the icons.

I read a lot of thread about this topic, but dont find the exact solution what I prefer. The optimal for me will be a solution to block the render while the icons have arrived.

Try to use "&display=block" and of the href but it blocks the render while the fonts are ready, after that render the text and then the icon itself.

Anyway to solve this issue, or is it just possible with selfhosting the fonts/icons and use @font-face?

Also try to use npm package, but faced with the same issue, if the bandwidth was small.

Thanks. G

1

There are 1 answers

0
Fadi On

I think you need to preload the fonts and prevent the page from rendering until the fonts are ready.

Preload the Fonts

<link rel="preload" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" as="style" onload="this.onload=null;this.rel='stylesheet'">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" media="all" onload="this.media='all'" rel="stylesheet" type="text/css" as="style" crossorigin="anonymous" data-font-display="block">

The font-display property is to control how the font is displayed while it's loading. In your case, you can set it to "block" to block rendering until the fonts are available

Check if the fonts are loaded before allowing the rest of your content to render. This can be done using the FontFace API. Here's an example of how to do it:

const font = new FontFace('Material Symbols Rounded', 'url(https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200)');
font.load().then(() => {
  document.fonts.add(font);
  // Now, render your content or components using the Google Fonts icons
})