Load fonts on demand

大城市里の小女人 提交于 2019-12-11 02:12:43

问题


My application has to support many fonts. User can select any font from given list of fonts. Loading all fonts synchronously or asynchronously does not make sense because user may use one of many fonts and its just waste of bandwidth.

I have a select box with fonts name, I want to load font when user select font from select box.

Using typekit I can divide fonts in separate kits but how do I load these kits on javascript event ?

Can I achieve this using typekit , google fonts or any other service ?


回答1:


It's pretty simple. You just need to inject the corresponding CSS rules with JavaScript. If you have the font-face definitions in an external CSS file, you can simply dynamically add the <link> tag to the HTML head. This of course can be a CSS file directly from Google Fonts or TypeKit.

var link = document.createElement("link")
link.setAttribute("rel", "stylesheet")
link.setAttribute("type", "text/css")
link.setAttribute("href", "http://fonts.googleapis.com/css?family=Indie+Flower")
document.getElementsByTagName("head")[0].appendChild(link)



回答2:


Interesting problem -- I was just looking around on GIT and came across a WebFont loader JS that looks like it might solve your problem. It's fairly well documented and may provide an excellent solution. See here: https://github.com/typekit/webfontloader



来源:https://stackoverflow.com/questions/31144937/load-fonts-on-demand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!