Andrii Radkevych
Andrii Radkevych

Reputation: 3442

Eliminate render-blocking resources ( lighthouse)

<!DOCTYPE html>
<html>
  <head>
    <title>BookNotes</title>

    <meta charset="utf-8" />
    <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
    <meta httpEquiv="Content-Language" content="en" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    />
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

I have this html page , I want to use Roboto font stylesheets , but in the way like I use it Lighthouse give me this warning :

enter image description here

What is the best way to optimize it ? I've read that I can use defer or async attribute, for loading it in async way of after rendering , but if I will load it after rendering , it will not apply styles for my font , etc . Will be really appreciate your help. If you need additional info , pls let me know .

Upvotes: 2

Views: 1517

Answers (2)

Andrii Radkevych
Andrii Radkevych

Reputation: 3442

I've found better solution:

 <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
      media="print"
      onload="this.media='all'"
    />

This is working well

Upvotes: 2

Bram Vanroy
Bram Vanroy

Reputation: 28505

Personally, I think the best way to deal with this is loading the fonts asynchronously. However, this might lead to font blinking, meaning that a font is first the default and then gets rerendered to the newly loaded font. To remedy this, you can hide the contents of the page until the font is loaded, and show it with a callback. You can take a look at webfontloader. You also have to have fallback for the rare cases when someone has JS disabled.

JavaScript

var WebFont = require('webfontloader');

WebFont.load({
  google: {
    families: ['Roboto']
  }
});
document.querySelector('html').classList.remove('no-js')

CSS

html {opacity: 0;}
html .wf-active, html.wf-inactive, html.no-js {opacity: 1;}

HTML

<html lang="en" class="no-js">

Upvotes: 1

Related Questions