Search code examples
javascriptcssfont-face

Dynamically added font face not working


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.


Solution

  • 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);