页面加载后动态加载谷歌字体

时间:2013-05-14 21:41:32

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

我希望能够让用户选择他们希望在哪个字体中显示的内容。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);
      })();

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

2 个答案:

答案 0 :(得分:30)

在此github repo中查看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>

答案 1 :(得分:2)

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

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>