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
        link.href = `https://fonts.googleapis.com/css?family=${fontName.replace(/\s/g, "+")}`;
        // Append the new element to the head of the document

What this function does is take a font name i.e. Open Sans, and checks if the font is already loaded on the page. Then if it's not it creates a new font tag and inserts it in the head of the document. Once the font is loaded in any elements with the Open Sans font family set will automatically change, this also works in the canvas element. One thing to note is in the URL the spaces in the font name need to be replaced with pluses, which is taken care of using a RegExp.



Be the first to comment!

Read More


Generating Images Based on a URL Slug

Welcome to our tutorial on dynamically generating images using Node.js! In this post, we'll be exploring a technique for creating images on the fly based on the URL slug of a webpage. This can be a powerful tool for creating personalized, dynamic content for your website or application. Whether you're looking to create unique product images, customized social media graphics, or any other t...

Building SvelteKit for Node JS

SvelteKit is a powerful tool that is great for making all types of websites, with out of the box support for services like Vercel. In this tu...

Node JS Logo
Node JS Logo

Setting up Node.JS for production

Node.js is a popular JavaScript runtime that allows developers to build server-side applications with JavaScript. PM2 is a process manager for Node.js applications that helps to keep your applications running smoothly and automatically restart th...