最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use Webfont Loader with Gatsby? - Stack Overflow

programmeradmin3浏览0评论

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 patible 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?

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 patible 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?

Share Improve this question asked Jan 30, 2018 at 1:43 Eric JohnsonEric Johnson 1,15415 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Have a look at how these guys did it here: https://github./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./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.

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']
        }
      }
    }
  ]
发布评论

评论列表(0)

  1. 暂无评论