Web Components Community πŸ”·

AK DevCraft
AK DevCraft

Posted on • Updated on • Originally published at dev.to

Load external font with web component

Recently while working on an application I faced a very strange issue, where the expected external font was not getting applied 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 read about it HERE.

However, 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 attaching the 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 attach the link element to the head of the HTML page. Now once the font is loaded in the browser, you can use the font to style the web component.


        const font = document.createElement("link");
        font.href = "https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap";
        font.rel = "stylesheet"
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!

Latest comments (1)

derrickolley profile image

Very interesting and exciting article! I learned a lot for myself despite my busyness in creating manuals drawnbyhislight.com drawing how to draw easily and simply!