UNPKG

15.9 kBMarkdownView Raw
1# Web Font Loader
2
3Web Font Loader gives you added control when using linked fonts via `@font-face`. It provides a common interface to loading fonts regardless of the source, then adds a standard set of events you may use to control the loading experience. The Web Font Loader is able to load fonts from [Google Fonts](http://www.google.com/fonts/), [Typekit](http://www.typekit.com/), [Fonts.com](http://www.fonts.com/), and [Fontdeck](http://fontdeck.com/), as well as self-hosted web fonts. It is co-developed by [Google](http://www.google.com/) and [Typekit](http://www.typekit.com).
4
5[![Build Status](https://travis-ci.org/typekit/webfontloader.svg?branch=master)](https://travis-ci.org/typekit/webfontloader)
6
7## Contents
8
9* [Get started](#get-started)
10* [Configuration](#configuration)
11 * [Events](#events)
12 * [Timeout](#timeouts)
13 * [Iframes](#iframes)
14* [Modules](#modules)
15 * [Custom](#custom)
16 * [Fontdeck](#fontdeck)
17 * [Fonts.com](#fontscom)
18 * [Google](#google)
19 * [Typekit](#typekit)
20* [Browser support](#browser-support)
21* [License](#copyright-and-license)
22
23## Get Started
24
25To use the Web Font Loader library, just include it in your page and tell it which fonts to load. For example, you could load fonts from [Google Fonts](http://www.google.com/fonts/) using the Web Font Loader hosted on [Google Hosted Libraries](https://developers.google.com/speed/libraries/) using the following code.
26
27```html
28<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"></script>
29<script>
30 WebFont.load({
31 google: {
32 families: ['Droid Sans', 'Droid Serif']
33 }
34 });
35</script>
36```
37
38Alternatively, you can link to the latest `1.x` version of the Web Font Loader by using `https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js` as the `script` source. Note that the version in this url is less specific. It will always load the latest `1.x` version, but it also has a shorter cache time to ensure that your page gets updates in a timely manner. For performance reasons, we recommend using an explicit version number (such as `1.4.7`) in urls when using the Web Font Loader in production. You can manually update the Web Font Loader version number in the url when you want to adopt a new version.
39
40It is also possible to use the Web Font Loader asynchronously. For example, to load [Typekit](http://www.typekit.com) fonts asynchronously, you could use the following code.
41
42```html
43<script>
44 WebFontConfig = {
45 typekit: { id: 'xxxxxx' }
46 };
47
48 (function(d) {
49 var wf = d.createElement('script'), s = d.scripts[0];
50 wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js';
51 s.parentNode.insertBefore(wf, s);
52 })(document);
53</script>
54```
55
56Using the Web Font Loader asynchronously avoids blocking your page while loading the JavaScript. Be aware that if the script is used asynchronously, the rest of the page might render before the Web Font Loader is loaded and executed, which can cause a [Flash of Unstyled Text (FOUT)](http://help.typekit.com/customer/portal/articles/6852).
57
58The FOUT can be more easily avoided when loading the Web Font Loader synchronously, as it will automatically set the `wf-loading` class on the HTML element as soon as `Webfont.load` has been called. The browser will wait for the script to load before continuing to load the rest of the content, FOUT is avoided.
59
60## Configuration
61
62The Web Font Loader configuration is defined by a global variable named `WebFontConfig`, or passed directly to the `WebFont.load` method. It defines which fonts to load from each web font provider and gives you the option to specify callbacks for certain events. When using the asynchronous approach, you must define the global variable `WebFontConfig` before the code that loads the Web Font Loader (as in the example above).
63
64### Events
65
66Web Font Loader provides an event system that developers can hook into. It gives you notifications of the font loading sequence in both CSS and JavaScript.
67
68 * `loading` - This event is triggered when all fonts have been requested.
69 * `active` - This event is triggered when the fonts have rendered.
70 * `inactive` - This event is triggered when the browser does not support linked fonts *or* if none of the fonts could be loaded.
71 * `fontloading` - This event is triggered once for each font that's loaded.
72 * `fontactive` - This event is triggered once for each font that renders.
73 * `fontinactive` - This event is triggered if the font can't be loaded.
74
75CSS events are implemented as classes on the `html` element. The following classes are set on the `html` element:
76
77```css
78.wf-loading
79.wf-active
80.wf-inactive
81.wf-<familyname>-<fvd>-loading
82.wf-<familyname>-<fvd>-active
83.wf-<familyname>-<fvd>-inactive
84```
85
86The `<familyname>` placeholder will be replaced by a sanitized version of the name of each font family. Spaces and underscores are removed from the name, and all characters are converted to lower case. For example, `Droid Sans` becomes `droidsans`. The `<fvd>` placeholder is a [Font Variation Description](https://github.com/typekit/fvd). Put simply, it's a shorthand for describing the style and weight of a particular font. Here are a few examples:
87
88```css
89/* n4 */
90@font-face { font-style: normal; font-weight: normal; }
91
92/* i7 */
93@font-face { font-style: italic; font-weight: bold; }
94```
95
96Keep in mind that `font-weight: normal` maps to `font-weight: 400` and `font-weight: bold` maps to `font-weight: 700`. If no style/weight is specified, the default `n4` (`font-style: normal; font-weight: normal;`) will be used.
97
98If fonts are loaded multiple times on a single page, the CSS classes continue to update to reflect the current state of the page. The global `wf-loading` class is applied whenever fonts are being requested (even if other fonts are already active or inactive). The `wf-inactive` class is applied only if none of the fonts on the page have rendered. Otherwise, the `wf-active` class is applied (even if some fonts are inactive).
99
100JavaScript events are implemented as callback functions on the `WebFontConfig` configuration object.
101
102```javascript
103WebFontConfig = {
104 loading: function() {},
105 active: function() {},
106 inactive: function() {},
107 fontloading: function(familyName, fvd) {},
108 fontactive: function(familyName, fvd) {},
109 fontinactive: function(familyName, fvd) {}
110};
111```
112
113The `fontloading`, `fontactive` and `fontinactive` callbacks are passed the family name and font variation description of the font that concerns the event.
114
115It is possible to disable setting classes on the HTML element by setting the `classes` configuration parameter to `false` (defaults to `true`).
116
117```javascript
118WebFontConfig = {
119 classes: false
120};
121```
122
123You can also disable font events (callbacks) by setting the `events` parameter to `false` (defaults to `true`).
124
125```javascript
126WebFontConfig = {
127 events: false
128};
129```
130
131If both events and classes are disabled, the Web Font Loader does not perform font watching and only acts as a way to insert @font-face rules in the document.
132
133### Timeouts
134
135Since the Internet is not 100% reliable, it's possible that a font will fail to load. The `fontinactive` event will be triggered after 5 seconds if the font fails to render. If *at least* one font succesfully renders, the `active` event will be triggered, else the `inactive` event will be triggered.
136
137You can change the default timeout by using the `timeout` option on the `WebFontConfig` object.
138
139```javascript
140WebFontConfig = {
141 google: {
142 families: ['Droid Sans']
143 },
144 timeout: 2000 // Set the timeout to two seconds
145};
146```
147
148The timeout value should be in milliseconds, and defaults to 3000 milliseconds (3 seconds) if not supplied.
149
150### Iframes
151
152Usually, it's easiest to include a copy of Web Font Loader in every window where fonts are needed, so that each window manages its own fonts. However, if you need to have a single window manage fonts for multiple same-origin child windows or iframes that are built up using JavaScript, Web Font Loader supports that as well. Just use the optional `context` configuration option and give it a reference to the target window for loading:
153
154```javascript
155WebFontConfig = {
156 google: {
157 families: ['Droid Sans']
158 },
159 context: frames['my-child']
160};
161```
162
163This is an advanced configuration option that isn't needed for most use cases.
164
165## Modules
166
167Web Font Loader provides a module system so that any web font provider can contribute code that allows their fonts to be loaded. This makes it possible to use multiple web font providers at the same time. The specifics of each provider currently supported by the library are documented here.
168
169### Custom
170
171To load fonts from any external stylesheet, use the `custom` module. Here you'll
172need to specify the font family names you're trying to load, and optionally the url of the stylesheet that provides the `@font-face` declarations for those fonts.
173
174You can specify a specific font variation or set of variations to load and watch
175by appending the variations separated by commas to the family name separated by
176a colon. Variations are specified using [FVD notation](https://github.com/typekit/fvd).
177
178```javascript
179WebFontConfig = {
180 custom: {
181 families: ['My Font', 'My Other Font:n4,i4,n7'],
182 urls: ['/fonts.css']
183 }
184};
185```
186
187In this example, the `fonts.css` file might look something like this:
188
189```css
190@font-face {
191 font-family: 'My Font';
192 src: ...;
193}
194@font-face {
195 font-family: 'My Other Font';
196 font-style: normal;
197 font-weight: normal; /* or 400 */
198 src: ...;
199}
200@font-face {
201 font-family: 'My Other Font';
202 font-style: italic;
203 font-weight: normal; /* or 400 */
204 src: ...;
205}
206@font-face {
207 font-family: 'My Other Font';
208 font-style: normal;
209 font-weight: bold; /* or 700 */
210 src: ...;
211}
212```
213
214If your fonts are already included in another stylesheet you can also leave out the `urls` array and just specify font family names to start font loading. As long as the names match those that are declared in the `families` array, the proper loading classes will be applied to the html element.
215
216```html
217<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
218<script>
219 WebFont.load({
220 custom: {
221 families: ['My Font']
222 }
223 });
224</script>
225
226<style type="text/css">
227 @font-face {
228 font-family:"My Font";
229 src:url("assets/fonts/my_font.woff") format("woff");
230 }
231</style>
232```
233
234The custom module also supports customizing the test strings that are used to determine whether or not a font has loaded. This can be used to load fonts with custom subsets or glyphs in the private use unicode area.
235
236```javascript
237WebFontConfig = {
238 custom: {
239 families: ['My Font'],
240 testStrings: {
241 'My Font': '\uE003\uE005'
242 }
243 }
244};
245```
246
247Tests strings should be specified on a per font basis and contain at least one character. If not specified the default test string (`BESbswy`) is used.
248
249### Fontdeck
250
251To use the [Fontdeck](http://fontdeck.com/) module, specify the ID of your website. You can find this ID on the website page within your account settings.
252
253```javascript
254WebFontConfig = {
255 fontdeck: {
256 id: 'xxxxx'
257 }
258};
259```
260
261### Fonts.com
262
263When using [Fonts.com web fonts](http://webfonts.fonts.com/) specify your Project ID.
264
265```javascript
266WebFontConfig = {
267 monotype: {
268 projectId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
269 version: 12345 // (optional, flushes the CDN cache)
270 }
271};
272```
273
274The Fonts.com module has an optional `version` option which acts as a cache-buster.
275
276### Google
277
278Using [Google's Font API](https://code.google.com/apis/webfonts/docs/getting_started.html), name the font families you'd like to load. You can use the same [syntax](https://developers.google.com/fonts/docs/getting_started#Syntax) as in the Font API to specify styles:
279
280```javascript
281WebFontConfig = {
282 google: {
283 families: ['Droid Sans', 'Droid Serif:bold']
284 }
285};
286```
287
288Sometimes the font you requested doesn't come in the default weight (e.g. 400) and you need to explicitly request the variation you want for font events to work (e.g. `300`, `700`, etc.):
289
290```javascript
291WebFontConfig = {
292 google: {
293 families: ['Open Sans Condensed:300,700']
294 }
295};
296```
297
298If you need to specify character subsets other than the default (e.g.: greek script in addition to latin), you must append the subset string to the requested family string after a colon. The subset string should follow the [Google documentation](https://developers.google.com/fonts/docs/getting_started#Subsets) (subset names separated by commas):
299
300```javascript
301WebFontConfig = {
302 google: {
303 families: ['Open Sans Condensed:300,700:latin,greek']
304 }
305};
306```
307
308You can also supply the `text` parameter to perform character subsetting:
309
310```javascript
311WebFontConfig = {
312 google: {
313 families: ['Droid Sans', 'Droid Serif'],
314 text: 'abcdedfghijklmopqrstuvwxyz!'
315 }
316};
317```
318
319The `text` subsetting functionality is only available for the Google module.
320
321### Typekit
322
323When using [Typekit](http://www.typekit.com), specify the Kit to retrieve by its ID. You can find the Kit ID within Typekit's Kit Editor interface.
324
325```javascript
326WebFontConfig = {
327 typekit: {
328 id: 'xxxxxx'
329 }
330};
331```
332
333**FYI:** Typekit's own JavaScript is built using the Web Font Loader library and already provides all of the same font event functionality. If you're using Typekit, you should use their embed codes directly unless you also need to load web fonts from other providers on the same page.
334
335## Browser Support
336
337Every web browser has varying levels of support for fonts linked via `@font-face`. Web Font Loader determines support for web fonts is using the browser's user agent string. The user agent string may claim to support a web font format when it in fact does not. This is especially noticeable on mobile browsers with a "Desktop" mode, which usually identify as Chrome on Linux. In this case a web font provider may decide to send WOFF fonts to the device because the real desktop Chrome supports it, while the mobile browser does not. The Web Font Loader is not designed to handle these cases and it defaults to believing what's in the user agent string. Web font providers can build on top of the basic Web Font Loader functionality to handle these special cases individually.
338
339If Web Font Loader determines that the current browser does not support `@font-face`, the `inactive` event will be triggered.
340
341When loading fonts from multiple providers, each provider may or may not support a given browser. If Web Font Loader determines that the current browser can support `@font-face`, and *at least* one provider is able to serve fonts, the fonts from that provider will be loaded. When finished, the `active` event will be triggered.
342
343For fonts loaded from supported providers, the `fontactive` event will be triggered. For fonts loaded from a provider that *does not* support the current browser, the `fontinactive` event will be triggered.
344
345For example:
346
347```javascript
348WebFontConfig = {
349 providerA: 'Family1',
350 providerB: 'Family2'
351};
352```
353
354If `providerA` can serve fonts to a browser, but `providerB` cannot, The `fontinactive` event will be triggered for `Family2`. The `fontactive` event will be triggered for `Family1` once it loads, as will the `active` event.
355
356## Copyright and License
357
358Web Font Loader Copyright (c) 2010 Adobe Systems Incorporated, Google Incorporated.
359
360Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
361
362 http://www.apache.org/licenses/LICENSE-2.0
363
364Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.