1

I'm building a widget which users can design and then embed on their own website. One thing they can choose is the font, which we self host on AWS.

During the initial load, the app hits our API for the widget details, the font URL is returned in the response. We are then setting this as a CSS variable like so:

HTML:

<div v-bind:style="cssProps">

Vus JS :

cssProps(){
  return {
    '--accent_color': "#" + this.$store.state.accent_color,
    '--font-url': (this.$store.state.font != null ? "https://wifiuploads.s3.amazonaws.com/" + this.$store.state.font : '"Source Sans Pro", sans-serif'),
  }
}

The main issue I have come across it I cannot interpolate a dynamic url like this:

@font-face {
  font-family: "user_selection";
  src: url(var(--font-url));
}

I cannot use a static url for the fonts, I need away to load fonts into my stylesheets with a dynamic URL.

will
  • 49
  • 11
  • Maybe a dynamic @font-face rule with style tag could be created using JS? CSS variables can be read from JS – Kunukn Apr 28 '21 at 21:06
  • register all fonts and with different classes use them – AhmadKZX Apr 29 '21 at 11:25
  • @AhmadKZX yeah I think this is the only way in which it might work. Trouble is, I think this might run into hundreds of fonts being imported for now reason. – will Apr 29 '21 at 11:57
  • @Kunukn - thank you for pointing me in the right direction. I've. written up my solution below. – will Apr 29 '21 at 12:05

1 Answers1

0

To resolve I created a style element with a font-face rule using Javascript:

JS:

created(){
      var newStyle = document.createElement('style');
      newStyle.appendChild(document.createTextNode("\
      @font-face {\
          font-family: 'user_selection';\
          src: url('https://wifiuploads.s3.amazonaws.com/" + this.$store.state.font + "');\
      }\
      "));

      document.head.appendChild(newStyle);

    },

CSS:

body{
    font-family: "user_selection";
  }
will
  • 49
  • 11