按需加载字体 [英] Load fonts on demand

查看:271
本文介绍了按需加载字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序必须支持许多字体.用户可以从给定的字体列表中选择任何字体.同步或异步加载所有字体是没有意义的,因为用户可能会使用多种字体之一,这只会浪费带宽.

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.

使用Typekit,我可以将字体划分为单独的工具包,但是如何在javascript事件中加载这些工具包?

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

我可以使用typekit,谷歌字体或任何其他服务来实现吗?

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

推荐答案

这很简单.您只需要使用JavaScript注入相应的CSS规则即可.如果您在外部CSS文件中具有字体定义,则可以简单地将<link>标记动态添加到HTML头中.当然,这可以是直接来自Google Fonts或TypeKit的CSS文件.

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)

这篇关于按需加载字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆