function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Surya Chandra Rao GandreddiSurya Chandra Rao Gandreddi 

Load Fonts in Component

I'm trying to load fonts (dynamically) from the static resource,
addFont: function(name, link) {
        var css = '@font-face { font-family: ' + name + '; src: url("' + link + '");';
        console.log('addFont css: ', css);

        var head = document.head || document.getElementsByTagName('head')[0];
        var style = document.createElement('style');

        style.type = 'text/css';
        if (style.styleSheet){
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }

        head.appendChild(style);
    }

The fonts are not loading, but if I hard code the same in the component they work fine. Am I missing something?
Fonts are loaded (from an AuraEnabled controller Method) on onInit which calls addFont.
NagendraNagendra (Salesforce Developers) 
Hi Surya,

In your case font files are already available as static resources. So you can create the font families in advance (inside CSS file) and only change the fontFamily property dynamically through JavaScript action. Here is an example.

Component:
<aura:component >
    <p id="cf">This is a custom font in Lightning Components</p>
    <select id="dropdown" onchange = "{!c.fontSelected}">
        <option value="">Select Font</option>
        <option value="Default Font">Default Font</option>
        <option value="Custom Font">Custom Font</option>        
    </select>    
</aura:component>
CSS File:
@font-face {
  font-family: 'myfont';
  src: url(/resource/myfont/font/sansation_light.woff);
}
JS Controller:
({
    fontSelected : function(component, event, helper) {
        var dropdown = document.getElementById("dropdown");
        if(dropdown.options[dropdown.selectedIndex].innerHTML == "Custom Font"){
            document.getElementById("cf").style.fontFamily = "myfont";
        }else{
            document.getElementById("cf").style.fontFamily = "Salesforce Sans";
        }
    }
})
Thanks,
Nagendra


 
Surya Chandra Rao GandreddiSurya Chandra Rao Gandreddi
But the fonts are loaded from the CustomSettings which refer to the StaticResource which means the Fonts are dynamic/end-user defined.