Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Webfont Loader with Gatsby?

I want to use Webfont Loader to manage the loading of a custom font and also to load a couple Google fonts. However, I'm not sure how to integrate it with Gatsby. I found a React wrapper for Webfont Loader, but it wants you to use it like this:

<WebfontLoader config={config} onStatus={callback}>
  <App />
</WebfontLoader>

which doesn't seem to me to be compatible with Gatsby. Is there a way to adapt it so it will work with Gatbsy? Or a way to adapt the unwrapped npm webfontloader module to work with Gatsby?

like image 952
Eric Johnson Avatar asked Jan 30 '18 01:01

Eric Johnson


2 Answers

Have a look at how these guys did it here: https://github.com/smartive/smartive.ch/blob/master/src/layouts/index.js

That example is still a little above my knowledge so I tried a simpler way and it works just fine for me (though might not be the "cleanest" approach etc)

in my layouts/index.js I import:

import './main.js'

in which I have the following:

if (typeof window !== `undefined`) {

window.onload=function(){

  var WebFont = require('webfontloader');

  WebFont = {
      typekit: { id: 'psj0mst' }
   };

   (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);

}
}

I had to add the check for window because otherwise I got an error when building the gatsby site for production.

like image 148
Martin Conde Avatar answered Nov 11 '22 18:11

Martin Conde


There is now a gatsby plugin to do this work:

Install

npm install --save gatsby-plugin-web-font-loader

And Use

    plugins: [
    {
      resolve: 'gatsby-plugin-web-font-loader',
      options: {
        google: {
          families: ['Droid Sans', 'Droid Serif']
        }
      }
    }
  ]
like image 41
Theo Avatar answered Nov 11 '22 19:11

Theo