Skip to content

Instantly share code, notes, and snippets.

@kristofgilicze
Created December 1, 2021 23:38
Show Gist options
  • Save kristofgilicze/0e52a12e88a1b8afb96b0961b731dd95 to your computer and use it in GitHub Desktop.
Save kristofgilicze/0e52a12e88a1b8afb96b0961b731dd95 to your computer and use it in GitHub Desktop.
Load font face for use in WebComponents
function loadFontFace(
fontName: string,
url: string,
fontWeight: string = 'normal',
fontStyle: string = 'normal',
format: string = 'woff2'
) {
// Add custom font to page DOM since font-face doesn't work within Shadow DOM.
let element = document.getElementById(`custom-loaded-${fontName}`);
// Only inject the element if it's not yet present
if (!element) {
element = document.createElement('style');
element.innerHTML = `
@font-face {
font-family: '${fontName}';
font-style: ${fontStyle};
font-weight: ${fontWeight};
src: local('${fontName}'), url('${url}') format('${format}');
}
`;
document.head.appendChild(element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment