fontsloadinggoogle-font-apitypekit

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 ?


Solution

  • 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)