Dynamically load google fonts after page has loaded
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>
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;