Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

AK DevCraft
AK DevCraftSubscriber

Posted on • Edited 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 itHERE.

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 alink 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 thelink 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();constfont=document.createElement("link");font.href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap";font.rel="stylesheet"document.head.appendChild(font);}
Enter fullscreen modeExit 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:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack Software Engineer, creating digital solutions across various platforms. Programming and software engineering are essential part of my life just like air 😎
  • Work
    Software Engineer
  • Joined

More fromAK DevCraft

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp