Home > Enterprise >  Load local font from assets in mounted method in vue
Load local font from assets in mounted method in vue

Time:09-29

How do I load a local font on mounted:

I have the font in the assets folder and have tried this amongst other ways.

I'm using this FontFace API as i want the font to load first before using it (https://stackoverflow.com/a/36248266/66975)

mounted () {
  const myFont = new FontFace('adobe-arabic', 'url(~@/assets/Fonts/AdobeArabicRegular/AdobeArabicRegular.ttf)');

  myFont.load().then((font) => {
    document.fonts.add(font);
    console.log('Font loaded');
  });
},

CodePudding user response:

For fonts you'd ideally want to load them in via CSS, the browser will automatically handle async loading and you can even leverage preloading to guarantee that the font will be available before navigating to the page.

mounted() isn't a great place to load assets either, since the end of the mounted hook means data/the template is about to be displayed to the user. Fonts can be very large, so by the time mounted finishes up, the user might still be downloading the font, which will lead to FOUT.

If you absolutely have to load your font programmatically via javascript, then you should use Google and Typekit's WebFontLoader library: https://github.com/typekit/webfontloader. I also recommend sticking that code into a beforeCreate() hook, rather than mounted() to avoid FOUT and similar issues

CodePudding user response:

Asset URLs need to be manually resolved in script using require(assetUrl), and you would have to remove the ~ prefix:

// MyComponent.vue
export default {
  mounted() {
    const fontUrl = require('@/assets/Fonts/AdobeArabicRegular/AdobeArabicRegular.ttf').default
    const myFont = new FontFace('adobe-arabic', `url(${fontUrl})`);
    //...
  }
}

However in the SFC's <style> block, the asset URL resolution happens automatically when the URL is prefixed with ~ (as you had attempted). So you could replace the above with:

// MyComponent.vue
<style>
@font-face {
  font-family: "adobe-arabic";
  src: url("~@/assets/Fonts/AdobeArabicRegular/AdobeArabicRegular.ttf");
}
</style>
  • Related