1

I am getting custom font via API as a String given below,

"@font-face {
  font - family: 'Custom Font Name';
  src: url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.eot');
  src: url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.eot?#iefix') format('embedded-opentype'),
  url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.ttf') format('opentype'),
  url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.woff') format('woff');
  font - weight: normal;
  font - style: normal;
}
"

I need to put this font-family definition in style tag of a php/html file or write/append in an existing CSS file so that I can use the Custom Font Name as a value for font-family property. I have to populate select dropdown for selecting these custom fonts received in API. I am using Javascript, jQuery for Scripting.

Please guide for the way out, as what is getting received is a string and not getting recognised as css.

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
Vrajesh Doshi
  • 744
  • 2
  • 8
  • 27

2 Answers2

2

Stylesheet Injection?

This ought to do it. Creating a stylesheet and setting its innerHTML to your CSS String. Enjoy!

function injectCSS( str ) {
    const style = document.createElement( 'style' );
    style.innerHTML = str;
    document.body.appendChild( style );
}

injectCSS( cssStr );

const cssStr = `@font-face {
  font - family: 'Custom Font Name';
  src: url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.eot');
  src: url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.eot?#iefix') format('embedded-opentype'),
  url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.ttf') format('opentype'),
  url('https://base_url/fonts/pGdyQlal_QW0WERKk_405638ad.woff') format('woff');
  font - weight: normal;
  font - style: normal;
}`;
Michael Paccione
  • 2,467
  • 6
  • 39
  • 74
1

You don't have to. Please check the documentation of your webfont provider. You will find a script which when put in side your html makes the font automatically available to your page.

Aditya
  • 771
  • 5
  • 11