@font-face 没有在 shadowDom 中加载
Posted
技术标签:
【中文标题】@font-face 没有在 shadowDom 中加载【英文标题】:@font-face not loading in shadowDom 【发布时间】:2022-01-22 11:34:27 【问题描述】: this.shadowRoot.innerhtml = `
<style>
@font-face
font-family: SpaceGrotesk;
src: url(/fonts/SpaceGrotesk-Medium.ttf);
@font-face
font-family: SpaceGroteskLight;
src: url(/fonts/SpaceGrotesk-Light.ttf);
*
box-sizing: border-box;
.tipme
position: relative;
font-size: 1.4rem;
font-family: SpaceGrotesk, sans-serif;
text-align: center;
background-color: #fff;
padding: 4rem 1.4rem 1.4rem;
box-shadow: 0px 4px 40px rgba(0, 0, 0, 0.08);
margin: 5rem 1.4rem 1.4rem;
width: 50rem;
h1
font-family: SpaceGroteskLight, sans-serif;
font-weight: 400;
font-size: 2.6rem;
margin: 1rem;
`;
...
The browser is not requesting the the font files.
I tried in incognito mode so its not a cache issue.
This is a distributed component running on multiple sites, so I cannot just load the font in the parent html. It needs to be encapsulated.
【问题讨论】:
【参考方案1】:我最终只是将样式加载字体动态添加到父页面:
this.fonts = `
@font-face
font-family: SpaceGrotesk;
src: url($this.host/fonts/SpaceGrotesk-Medium.ttf);
@font-face
font-family: SpaceGroteskLight;
src: url($this.host/fonts/SpaceGrotesk-Light.ttf);
`;
const style = document.querySelector('style[data-description="tipme-fonts"]');
if (!style)
const el = document.createElement('style');
el.dataset.description = 'tipme-fonts';
el.appendChild(document.createTextNode(this.fonts));
document.head.appendChild(el);
【讨论】:
以上是关于@font-face 没有在 shadowDom 中加载的主要内容,如果未能解决你的问题,请参考以下文章
::slotted CSS 选择器用于 shadowDOM 插槽中的嵌套子级