DEV Community

AK DevCraft
AK DevCraft Subscriber

Posted on • Edited on

10 1

Load external font with web component

Background

Recently while working on an application I faced a very strange issue, where the expected external font was not getting loaded on the web component. I’m still new to the web component world, so I started reading more about it and soon found there is no straightforward/elegant way to load external font for a web component. After reading almost all of the articles about and around font import in the web component, I finally figure out a way to hack it and make it work.
If you’re not familiar with the web component then I’ll suggest you to read this nice blog on it HERE.

Getting Started

There are a few ways to load external font for a web component, first way is to load the font from the outer DOM (which defeats the purpose of the web component, as we want it to be autonomous). The second way is to load the font from the web component itself by injecting a link to the outer DOM. Though it's a hack, still I feel a pretty good way to load an external font until web component add functionality to achieve it.

We need to inject the link element to the head of the consuming HTML page from the web component. Now once the font is loaded in the browser, you can use the font to style the web component.

E.g.

constructor(){
        super();
        const font = document.createElement("link");
        font.href = "https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap";
        font.rel = "stylesheet"
        document.head.appendChild(font);
    }
Enter fullscreen mode Exit fullscreen mode

Codepen example

Sample Code

The code snippet presented in this blog is available on Github, Sample Code.

If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. Happy Coding!

My Other Blogs:

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay