2
fontFaceString = "@font-face {font-family: 'Lobster';font-style: normal;font-weight: normal;src:url('../../fonts/new_fonts/LOBSTER/Lobster-regular.ttf');}";

var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode(fontFaceString));
document.head.appendChild(newStyle);

I have to add multiple fonts dynamically. I am just trying to add one font with above snippet, It's getting added to style tag but not rendering properly.

1
  • Provide an example with jsfiddle or of your actual page Commented Sep 21, 2017 at 7:18

1 Answer 1

4

There is a special function in JS for adding CSS rules called insertRule(), first add <style></style> (no need to do it from JS) in your head tag, then add this code:

var sheet = window.document.styleSheets[0];
sheet.insertRule("@font-face {font-family: 'Lobster';font-style: normal;font-weight: normal;src:url('../../fonts/new_fonts/LOBSTER/Lobster-regular.ttf');}", sheet.cssRules.length);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.