Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 892
Alexis Avatar asked May 14 '13 21:05

Alexis


People also ask

How do I sync Google Fonts?

Select Google Fonts in the left Sidebar, and you will see the Sync Google Fonts button in the center, click that button to begin downloading for the first time. After the downloading process is finished, Google Fonts will be shown, and you can activate or deactivate them as normal local fonts.

Are Google Fonts cached?

In Google's own words: The font files themselves are cached for one year, which cumulatively has the effect of making the entire web faster: When millions of websites all link to the same fonts, they are cached after visiting the first website and appear instantly on all other subsequently visited sites.


2 Answers

Check out the WebFont.load command in this github repo:

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> 
like image 164
mccannf Avatar answered Oct 02 '22 14:10

mccannf


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>
like image 37
Pierre Arnissolle Avatar answered Oct 02 '22 13:10

Pierre Arnissolle