简体   繁体   English

页面加载后动态加载 google fonts

[英]Dynamically load google fonts after page has loaded

I would like to be able to have the user select which font they would like the page to be displayed in. Here is the way that Google recommends you do it using JavaScript.我希望能够让用户 select 知道他们希望页面显示的字体。是 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);
      })();

How can I modify this so that I can re-get fonts after the page has loaded?如何修改它以便在页面加载后重新获取 fonts?

Check out the WebFont.load command in this github repo:查看此 github 存储库中的 WebFont.load 命令:

https://github.com/typekit/webfontloader https://github.com/typekit/webfontloader

You can load whatever font you want dynamically:你可以动态加载任何你想要的字体:

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

Or if you don't want third party libs :或者,如果您不想要第三方库:

 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>

// 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM