Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load fonts on demand

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 ?

like image 499
Anil Maurya Avatar asked Mar 15 '23 13:03

Anil Maurya


1 Answers

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)
like image 187
udondan Avatar answered Mar 18 '23 23:03

udondan