【问题标题】:Dynamically load google fonts after page has loaded页面加载后动态加载谷歌字体
【发布时间】:2013-05-09 07:59:30
【问题描述】:

我希望能够让用户选择他们希望页面显示的字体。Here 是 Google 建议您使用 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);
      })();

如何修改它以便在页面加载后重新获取字体?

【问题讨论】:

    标签: javascript jquery css font-face google-font-api


    【解决方案1】:

    或者如果您不想要第三方库:

    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>

    【讨论】:

      【解决方案2】:

      查看此 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>
      

      【讨论】:

      • 确保在生产中使用特定版本。否则将没有缓存。
      • @sanmai:那不是真的......最新版本的缓存最长可达 1 年。我认为问题更多的是有缺陷的版本会破坏您的网站。
      • @DD。只是检查一下你是对的;目前对于version 1 as above in the post,Google 会提前一年提供Expires 标头;以前不是这样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2014-10-29
      • 2014-06-14
      • 1970-01-01
      • 2013-07-16
      • 2017-01-31
      相关资源
      最近更新 更多