cikcirikcik
cikcirikcik

Reputation: 191

NextJS - How to asynchronously load webfonts with webfontloader?

I have a NextJS app in which I load fonts using webfontloader

function load() {
  const WebFont = require("webfontloader");

  WebFont.load({
     google: {
       families: fonts
     }
    });
}

However, it significantly affects performance. I've read that asynchronous loading is possible according to the webfontloader documentation =>

<script>
   WebFontConfig = {
      typekit: { id: 'xxxxxx' }
   };

   (function(d) {
      var wf = d.createElement('script'), s = d.scripts[0];
      wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js';
      wf.async = true;
      s.parentNode.insertBefore(wf, s);
   })(document);
</script>

Apparently, you cannot add such scripts in the Next's Head component.

Is it possible to achieve async webfont loading in Next?

Upvotes: 0

Views: 435

Answers (1)

Fralle
Fralle

Reputation: 937

You should probably add that script to the body instead of the head. Or at least mark it with the attribute defer to ensure that it executes after the DOM has been loaded.

e.g.

<script defer>
   ...
</script>

Upvotes: 0

Related Questions