javascriptfontswebfont-loader

How to load custom fonts by url using Google WebFontLoader


I need to load fonts (.ttf, .otf) in runtime on demand using WebFontLoader.

There are only fontFamily and url for every font.

Looks like WebFontLoader has an option to load fonts using .css files like:

WebFont.load({
    custom: {
        families: [
            'font-family-name'
        ],
        urls: [
            'path-to-css'
        ]
    }
});

Is there a way to do it without .css file but with direct path to font file?

I wouldn't like to use any external sites to store my font files.


Solution

  • The only possible way to load to load and detect that font has been loaded that I found is to create <style> element with @font-face inside and add it to the DOM.

    let markup = [
            '@font-face {\n',
            '\tfont-family: \'', font-family-name, '\';\n',
            '\tfont-style: \'normal\';\n',
            '\tfont-weight: \'normal\';\n',
            '\tsrc: url(\'', font-file-url, '\');\n',
            '}\n'
        ].join('');
    });
    
    let style =  document.createElement('style');
    style.setAttribute('type', 'text/css');
    style.innerHTML = markup;
    

    and then you can use WebFontLoader to listen for events:

    WebFont.load({
        custom: {
            families: [
                'font-family-name'
            ],
            active: () => {
                //triggers when font has been loaded successfully
            },
            inactive: () => {
                //triggers when font loading failed
            }
        }
    });