30

So the basic workflow is this:

  1. Asynchronous file upload of a font (this is already done).

  2. Get the URL (done).

  3. Change the font to the new URL.

I realize this needs to be done via font-face, but I can't seem to figure out how to access that via JavaScript.

1

4 Answers 4

43

You can create a new <style> element with the @font-face rule and append it to the document's head:

var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode("\
@font-face {\
    font-family: " + yourFontName + ";\
    src: url('" + yourFontURL + "') format('yourFontFormat');\
}\
"));

document.head.appendChild(newStyle);

Of course, you'll probably need to provide all the necessary font formats and URLs, too, unless you're only worried about support for modern desktop browsers (in which case you would just use WOFF – I assume that's reasonable, because of the other features you mentioned).

Sign up to request clarification or add additional context in comments.

1 Comment

Now, I understand. I was thinking he mean the html tag <font> with the face attribute and that he wanted to write it in Javascript. +1
20

Define a FontFace object:

new_font = new FontFace('conthrax', 'url(fonts/conthrax-sb.ttf)')

Call its load method to download the font:

new_font.load().then(function(loaded_face) {
    // use font here

}).catch(function(error) {

});

... this returns a Promise, which when resolved passes the loaded FontFace.

Add the loaded font to the document:

new_font.load().then(function(loaded_face) {
    // use font here
    document.fonts.add(loaded_face)
}).catch(function(error) {

});

Comments

2

Try something like this:

let font = new FontFace("ExampleFont", 'url(ExampleFont.woff2) format("woff2")');
font.load().then(function(loadedFont)
{
    document.fonts.add(loadedFont);
    //do something after the font is loaded
}).catch(function(error) {
    // error occurred
});

Comments

0

Using js to create style element in document and then append TextNode child to it. Simple function:

function loadFont(name,url){
    var newStyle = document.createElement('style');
    newStyle.appendChild(document.createTextNode('@font-face{font-family: '+name+'; src: url('+url+');}'));
    document.body.appendChild(newStyle)
}

Example using:

loadFont("bonbon","fonts/bonbon.ttf");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.