页面加载后动态加载Google字体

30

我希望用户能够选择他们想要在页面中显示的字体。 这里 是谷歌推荐使用JavaScript完成此操作的方法。

WebFontConfig = {
    google: {
        families: ['Tangerine', 'Cantarell']
    }
};

(function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
            '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })();

我该如何修改这个代码,以便在页面加载后重新获取字体?

3个回答

40

请查看此 Github 存储库中的 WebFont.load 命令:

https://github.com/typekit/webfontloader

您可以动态加载任何所需字体:

 <script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script> 
  <script> 
        WebFont.load({
                    google: { 
                           families: ['Droid Sans', 'Droid Serif'] 
                     } 
         }); 
   </script>

4
在生产环境中一定要使用特定版本,否则将无法进行缓存。 - sanmai
@sanmai:这不是真的...最新版本有1年的缓存。我认为问题更多的是一个有缺陷的发行版会破坏你的网站。 - DD.
1
@DD。刚刚检查了一下,你是对的;目前针对帖子中的版本1,Google会提供一年后的“过期”头;以前不是这样的。 - sanmai

13
如果你不想使用第三方库,可以采用以下方法:
function addStylesheetURL(url) {
  var link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = url;
  document.getElementsByTagName('head')[0].appendChild(link);
}

// Load Tangerine & Cantarell
addStylesheetURL('https://fonts.googleapis.com/css2?family=Cantarell&family=Tangerine&display=swap');
    h1 {
      font-family: 'Cantarell', sans-serif;
    }
    p {
      font-family: 'Tangerine', cursive;
      font-size: 30px;
    }
<!DOCTYPE html>
<html>
  <head>
    <title>Dynamically load google fonts after page has loaded</title>
    <link rel="preconnect" href="https://fonts.gstatic.com">
  </head>
  <body>
    <h1>Dynamically load google fonts after page has loaded</h1>
    <p>Some text.</p>
  </body>
</html>


3
// Load font:

  const fontName = 'Roboto';
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `https://fonts.googleapis.com/css?family=${fontName}`;
  document.head.appendChild(link);

// Set font on body element with Javascript:

  document.body.style.fontFamily = fontName;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接