在网页中导入许多谷歌字体

时间:2015-02-08 01:31:55

标签: css http browser fonts stylesheet

例如,假设我导入了50个这样的字体:

@import url("http://fonts.googleapis.com/css?family=Lora|Droid+Sans|Roboto...");

.font-lora{
   font-family: "Loral";
}

.font-droid-sans{
   font-family: "Droid Sans";
}

.font-roboto{
   font-family: "Roboto";
}

...

但页面中只使用了2或3个类。

我的问题是,如果在网页上导入那么多字体有任何非明显的副作用,实际上只会使用2-3个。

根据我的理解,当页面上有元素的浏览器时,浏览器只会请求字体。正确?

我这样做是允许用户选择字体的界面的一部分,我注意到更改类比切换样式表更顺畅

2 个答案:

答案 0 :(得分:2)

是/否。 IE将加载所有加载,因为您正在使用@import浏览器将伸出并获取该文件。不要加载您不使用的字体,因为这些是额外的请求。这是google says

  

这看似显而易见,但如果您实际上没有使用字体,请不要在API中请求它。如果您在Firefox或Chrome中进行测试,您可能会错过这一点,这只会加载在页面上呈现文本所需的字体文件。相比之下,Internet Explorer会加载所有请求的字体,即使它们实际上并未使用过。

另外,您可能最好下载所有这些字体,然后将它们全部加载,以便它们根据请求在服务器上。

答案 1 :(得分:2)

除了@BuiltInOneDay

当您将新的@ font-face自定义Web字体打入CSS时会发生什么?事实证明 - 并不多。只包含@ font-face块实际上并不会在几乎所有浏览器(IE8除外)中从服务器开始下载远程字体文件。

/* Does not download */
@font-face {
    font-family: 'open_sansregular';
    src: /* This article does not cover @font-face syntax */;
}

那么,如何启动字体下载呢?窥视这个来源:

<!-- Initiates download in Firefox, IE 9+ -->
<div style="font-family: open_sansregular"></div>

<!-- Initiates download in Chrome, Safari (WebKit/Blink et al) -->
<div style="font-family: open_sansregular">Content.</div>

这意味着WebKit和Blink足够聪明,即使文档中存在使用我们的新字体系列但节点为空的节点,该字体也不会下载。这很棒!

如果我们在JavaScript中动态创建节点怎么办?

/* Does not download */
var el = document.createElement('div');
el.style.fontFamily = 'open_sansregular';

/* Initiates download in Firefox, IE 9+ */
document.body.appendChild(el);

/* Initiates download in WebKit/Blink */
el.innerHTML = 'Content.';

除IE8之外的所有节点都等到新节点被附加到文档中(未分离),并且如前所述,WebKit / Blink浏览器甚至会等到节点有文本内容。

现在我们知道@ font-face是对的。现在让我们弄清楚。

...

阅读来自Opera的Zach Leatherman的来源,了解更多信息:https://dev.opera.com/articles/better-font-face/