问题
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