DEV Community

Cover image for Why Fonts Don’t Work in Web Components and How to Fix It
AK DevCraft
AK DevCraft Subscriber

Posted on • Edited on

Why Fonts Don’t Work in Web Components and How to Fix It

Background

Recently, while working on an application, I faced a very strange problem where the expected external font was not getting loaded on the web component. So, I started researching about it and soon found there is no straightforward/elegant way to load an external font for a web component. After reading tons of articles about font import in the web component, I finally figured 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 this nice blog on it HERE.

Why This Happens

The root cause lies in how Shadow DOM works.

  • Shadow DOM isolates styles
  • Fonts, however, are not purely local assets
  • Browsers expect fonts to be available at the document level

So even if you define @font-face inside a Web Component:
👉 It doesn’t reliably make the font available where it’s needed

In short:
Web Components isolate CSS, but fonts don’t fully respect that boundary.

A Practical Fix (That Works)

There are a few ways to load an external font for a web component.

1. Load fonts globally

The first way is to load the font from the outer DOM. However, this defeats the purpose of the web component, as we want it to be autonomous and standalone.

2. Inject into the Host App

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 workaround, I still feel a pretty good way to load an external font until web components add functionality to achieve it.

We need to inject the link element into 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

Key Takeaway

Web Components give you powerful isolation, but not everything fits neatly inside that boundary.

Fonts are one of those edge cases where:
You sometimes need to step outside the component to make things work.

Sample Code Repo

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

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

My Other Blogs:

Top comments (0)