最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

web - How to import font file using JavaScript? - Stack Overflow

programmeradmin10浏览0评论

CSS has a @font-face rule which allows us to "use" custom fonts.

Does JavaScript have this functionality?

More specifically, is it possible to "use" custom fonts without using the CSS @font-face rule?

CSS has a @font-face rule which allows us to "use" custom fonts.

Does JavaScript have this functionality?

More specifically, is it possible to "use" custom fonts without using the CSS @font-face rule?

Share Improve this question edited Jul 2, 2012 at 4:48 Pacerier asked Apr 7, 2011 at 19:57 PacerierPacerier 89.7k111 gold badges383 silver badges644 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 6

Update 2023: use FontFace

As found on CSS Font Loading API on MDN:

const url_to_font_name = 'URL to font'
const font_name = new FontFace('Font Name', `url(${url_to_font_name})`);
document.fonts.add(font_name);
// Work that does not require `font_name` to be loaded…
await font_name.load()
// Work that requires `font_name` to be loaded…

I'm separating the url_to_font_name variable out to indicate that it can be a dynamically generated string. This the biggest benefit I see to use JavaScript to load fonts pared to CSS.

if you know CSS you can use document.write to append a style sheet dynamically... I guess that would count as using CSS, but it would work

There is no way to cause the browser to load a font from the network other than with a @font-face rule. You could theoretically create that @font-face rule from JavaScript without having to use document.write (or document.createElement("style") etc), if instead you used the CSS Object Model; but I wouldn't count on that to be implemented in any browser at the moment.

No. There's not. Javascript can manipulate the DOM, but it doesn't care about formatting.

There is an experimental technology "CSS Font Loading API" that allows to load and use font in javascript. Currently working in chrome and firefox.

fetch('/static/media/ProximaNova-Regular.otf')
        .then(resp => resp.arrayBuffer())
        .then(font => {
            const fontFace = new FontFace('Proxima-Nova', font);
            document.fonts.add(fontFace);
            document.body.style.fontFamily = '"Proxima-Nova", Arial';
        })

yes you can:

document.body.style.fontFamily = '...';

here is a fiddle: http://jsfiddle/maniator/QMZ8N/

this only adds a predefined font to an element.

This does NOT add a font style to the page. for that you might have to use CSS

发布评论

评论列表(0)

  1. 暂无评论