Search code examples
javascriptfonts

How to load a font in pure Javascript


The code I tried looks like this:

    var custom_font = new FontFace('myFont', 
       'url(https://fonts.googleapis.com/css2?family=VT323&display=swap)');
    custom_font.load().then(function(loaded_face) {
       document.fonts.add(loaded_face);
       <etc>
    }
}).catch(function(error) {alert("Unable to load font!");});

}

The network download works just fine, but the console error message is:

Failed to decode downloaded font: https://fonts.googleapis.com/css2?family=VT323&display=swap

There are similar questions, but in every case the answer involves doing something in HTML or CSS, and that option is not available. It has to be pure JS.

There is a WebFont library which is a possible fallback, but I really would rather get there in native code.


Solution

  • Based on the comment, I put https://fonts.googleapis.com/css2?family=VT323&display=swap in the browser. It came back with:

    /* latin */
    @font-face {
      font-family: 'VT323';
      font-style: normal;
      font-weight: 400;
      font-display: swap;
      src: url(https://fonts.gstatic.com/s/vt323/v17/pxiKyp0ihIEF2isfFJU.woff2) format('woff2');
      unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
    }
    

    The string url(https://fonts.gstatic.com/s/vt323/v17/pxiKyp0ihIEF2isfFJU.woff2) is the answer to the question. Thanks!