Dynamically loading Google Fonts
Google Fonts is a great tool for web developers, it allows you to load in almost any font on to you website and use it with only a few lines of code. However, sometimes you need to load in a font after the page loads. Here is a quick way to do it.
Google Fonts are loaded in the head
tag of your page using a link
tag, this is typically done when the page loads. If you want to load in a font after you can still just insert a link
tag using some javascript. Here's how:
function loadFont(fontName) {
// First check if the element is in the page
if (document.querySelector(`link[href="https://fonts.googleapis.com/css?family=${fontName.replace(/\s/g, "+")}"]`) == null) {
// If not create a new link tag
const link = document.createElement('link');
// set the rel property to stylesheet
link.rel = 'stylesheet';
// Set the href to the google fonts URL with your custom font name