Home > other >  Font Optimization
Font Optimization

Time:11-15

I'm trying to do font optimization which loads in 2 stages. But with my code below, it loads the regular font 'regular text' as italicized similar to that of 'italic text'. 'bold text' works fine.

What's wrong?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width">
  <title></title>
  <style>
    p {font-family: Roboto, Helvetica, serif; }
  </style>

  <link rel="preload" href=“./Roboto-Regular-kern-latin.woff2" type=font/woff2 as="font" crossorigin> 
  <style>
    @font-face {
      font-family: Roboto;
      src: url(./Roboto-Regular-kern-latin.woff2) format("woff2");
      font-weight: 400;
      font-display: swap;
    }

  </style>
  <script>
    if("fonts" in document) {
      let regular = new FontFace(“Roboto”, "url(./Roboto-Regular.woff2) format('woff2')")
      let bold = new FontFace(“Roboto”, "url(./Roboto-Bold.woff2) format('woff2')", { weight: 700})      
      let italic = new FontFace("Roboto", "url(./Roboto-Italic.woff2) format('woff2')")     
      Promise.all([regular.load(), bold.load(), italic.load()]).then(fonts => {
        fonts.forEach(font =>{
         document.fonts.add(font)
        })
      }) 
    }
  </script>
</head>
<body>
    <p>regular text
    <br>
    <strong>bold text</strong> 
    <br>
    <em>italic text</em> 
    </p>
</body>
</html>

CodePudding user response:

You'll probably need to set the style descriptor for the italic font, like you set the weight for the bold one:

let italic = new FontFace(
  "Roboto",
  "url(./Roboto-Italic.woff2) format('woff2')",
  { style: "italic" },
);
  • Related