Stencil: StencilJS Custom Fonts not working

Created on 10 Dec 2019  路  3Comments  路  Source: ionic-team/stencil

Stencil version:

 @stencil/[email protected]

I'm submitting a:

[x] bug report
[ ] feature request
[] support request => Please do not submit support requests here, use one of these channels: https://stencil-worldwide.herokuapp.com/ or https://forum.ionicframework.com/

Current behavior:

Importing a custom font with the path: url(assets/fonts/FONTNAME.woff) However the Font Family does not appear. It seems like it just cannot get the path correct? I have tried a lot, ../assets, ../src/assets/ /dist/collection/assets etc, still the font is not being applied to my text.

Expected behavior:

The CSS using font-family: CUSTOMFONT would load and the text would have the custom font given.

triage

Most helpful comment

Sorry to bring bad news but as far as I know, there's currently no way to load custom fonts at all from within a shadow DOM. If you want to hack around the issue you can inject the required css into the <head> tag on component load.

Chrome bug report https://bugs.chromium.org/p/chromium/issues/detail?id=336876

All 3 comments

Sorry to bring bad news but as far as I know, there's currently no way to load custom fonts at all from within a shadow DOM. If you want to hack around the issue you can inject the required css into the <head> tag on component load.

Chrome bug report https://bugs.chromium.org/p/chromium/issues/detail?id=336876

hi, any work arounds for this

You can dynamically inject your CSS into the <head> tag as I suggested.
Something like this should work:

    componentDidLoad() {
      // Add custom font to page DOM since font-face doesn't work within Shadow DOM.
      const fontCssUrl = 'https://example.com/font.css';
      let element = document.querySelector(`link[href="${fontCssUrl}"]`);

      // Only inject the element if it's not yet present
      if (!element) {
        element = document.createElement('link');
        element.setAttribute('rel', 'stylesheet');
        element.setAttribute('href', fontCssUrl);
        document.head.appendChild(element);
      }
    }
Was this page helpful?
0 / 5 - 0 ratings