DEV Community

AK DevCraft
AK DevCraft

Posted on • Updated on

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:

Oldest comments (0)