• This repository has been archived on 06/Mar/2024
  • Stars
    star
    372
  • Rank 114,858 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple utility to execute a callback when a webfont loads.

fontfaceonload

Build Status Dependency Status devDependency Status

Demo

Usage

Use with any existing @font-face declaration.

@font-face {
    font-family: My Custom Font Family;
    /* src and other properties as normal */
}

Include the library. Call the JavaScript.

FontFaceOnload("My Custom Font Family", {
    success: function() {},
    error: function() {},
    timeout: 5000 // in ms. Optional, default is 10 seconds
});

Use with Content Fonts

To allow the fallback font to be visible while the @font-face is loading, simply use FontFaceOnload like so:

FontFaceOnload("My Custom Font Family", {
    success: function() {
        document.documentElement.className += " my-custom-font-family";
    }
});

and then use the class to scope your usage of the custom font:

body {
    font-family: sans-serif;
}
.my-custom-font-family body {
    font-family: My Custom Font Family, sans-serif;
}

An alternative approach that will also eliminate the FOIT as well as not require you to change your CSS is to use the loadCSS library to load the @font-face with a Data URI source block dynamically. loadCSS is smaller than fontfaceonload. The limitations to this approach include requiring you to manage which format to load (WOFF, WOFF2, TTF) and it will not work as well with icon fonts (since you need to a CSS class to style other sibling elements, like the descriptive text).

Use with Icon Fonts

To hide the fallback font so that weird fallback characters are not visible while the icon font is loading, use FontFaceOnload with the glyphs option like so:

FontFaceOnload("My Custom Font Icon", {
    success: function() {
        document.documentElement.className += " my-custom-font-icon";
    },
    glyphs: "\uE600\uE601\uE602\uE605" // Optional, default is "". Useful for icon fonts: a few code points from your custom font icon.
});

and then use the class to scope your usage of the custom font:

.icon {
    display: none;
}
.my-custom-font-family .icon {
    display: inline-block;
    font-family: My Custom Font Icon, sans-serif;
}

How it Works

This uses the CSS Font Loading Module when available (currently in Chrome 35+ and Opera 22+). When that isn’t available, it uses a very similar approach to the one used in the TypeKit Web Font Loader (which is currently 7.1KB GZIP).

Basically, it creates an element with a font stack including the web font and a default serif/sans-serif typeface. It then uses a test string and measures the dimensions of the element at a certain interval. When the dimensions are different than the default fallback fonts, the font is considered to have loaded successfully.

If you’d like a full polyfill for the CSS Font Loading Module, follow along with Bram Stein’s Font Loader. I believe the specification has changed since he launched this polyfill, but he’s working on an updated version.

Building the project

Run these commands:

  • npm install
  • bower install
  • grunt init
  • grunt as normal.

Configuring Grunt

Rather than one giant Gruntfile.js, this project is using a modular Grunt setup. Each individual grunt configuration option key has its own file located in grunt/config-lib/ (readonly upstream configs, do not modify these directly) or grunt/config/ (project specific configs). You may use the same key in both directories, the objects are smartly combined using Lo-Dash merge.

For concatenation in the previous Gruntfile setup, you’d add another key to the giant object passed into grunt.initConfig like this: grunt.initConfig({ concat: { /* YOUR CONFIG */ } });. In the new configuration, you’ll create a grunt/config/concat.js with module.exports = { /* YOUR CONFIG */ };.

License

MIT License

Alternatives

More Repositories

1

web-font-loading-recipes

A bunch of demos for different web font loading strategies. Companion to https://www.zachleat.com/web/comprehensive-webfonts/
HTML
1,057
star
2

speedlify

Benchmark the web performance and accessibility of sites over time.
JavaScript
923
star
3

BigText

jQuery plugin, calculates the font-size and word-spacing needed to match a line of text to a specific width.
JavaScript
886
star
4

table-saw

A small web component for responsive <table> elements.
HTML
312
star
5

details-utils

A suite of utilities to add more features to the <details> element.
JavaScript
258
star
6

browser-window

Used in demos as a way to fake a Safari-esque web browser window.
JavaScript
249
star
7

zachleat.com

zachleat.com is powered by Eleventy and WebC.
JavaScript
192
star
8

Humane-Dates

Show the difference between a date and now (4 days ago)
JavaScript
186
star
9

carouscroll

Add next/previous buttons to a horizontal scrollable container.
HTML
116
star
10

performance-leaderboard

A plugin to run Lighthouse against a set of urls to see which site is the fastest.
JavaScript
96
star
11

postcss-foft-classes

A postcss plugin to automatically add classes for various font loading strategies.
JavaScript
90
star
12

seven-minute-tabs

A minimal no-theme Tabs web component.
JavaScript
87
star
13

filter-container

Filtering visible child elements based on form field values.
HTML
84
star
14

video-radio-star

A lightweight web component helper for HTML5 videos.
HTML
73
star
15

font-family-reunion

Compatibility tables for default local fonts.
HTML
67
star
16

spider-pig

Get a list of local URL links from a root URL.
JavaScript
67
star
17

snow-fall

A web component to add snow to your web site (or to an element on your web site).
JavaScript
67
star
18

announcement-banner

An announcement banner web component.
HTML
50
star
19

speedlify-score

A web component that shows Lighthouse scores via Speedlify.
JavaScript
45
star
20

hypercard

Web component to add a three-dimensional hover effect to a card.
JavaScript
41
star
21

jQuery-Gravatar

Retrieve a gravatar image dynamically from any e-mail address.
JavaScript
37
star
22

squirminal

The squirminal is a fake antique terminal web component
HTML
37
star
23

bench-framework-markdown

A set of scripts to test markdown processing speeds in various site generators/frameworks
Shell
34
star
24

infinity-burger

A new kind of hamburger menu
JavaScript
31
star
25

queue-code

Allows you to “type” syntax highlighted source code for presentations and screencasts.
JavaScript
30
star
26

pagefind-search

A web component to search with Pagefind.
JavaScript
30
star
27

performance-leaderboard-pagespeed-insights

A plugin to run Lighthouse on Pagespeed Insights against a set of urls to see which site is the fastest.
JavaScript
27
star
28

esm-import-transformer

Change import URLs in JavaScript code using import maps. e.g. `import * from "before"` to `import * from "after"`
JavaScript
24
star
29

idea-book

A public dump of ideas for side projects, for public upvoting/downvoting/commenting.
24
star
30

selecthor

A better way to test, learn, and demo CSS selectors
HTML
24
star
31

github-issue-to-json-file

Convert a well formed GitHub Issue Form populated Markdown body into a JSON data file in the repository.
JavaScript
23
star
32

JavaScript-Code-Katas

Let's practice our JavaScript testing.
JavaScript
23
star
33

webcare-webshare

JavaScript
23
star
34

f2em.com

A Front End Engineer's Manifesto
JavaScript
22
star
35

avatar-local-cache

Saves a image URL for an avatar to the local file system (and optimizes the image).
JavaScript
21
star
36

performance-sometime

Improving the web font rendering of the default Wordpress theme.
JavaScript
20
star
37

this-website-is-a-tech-talk

HTML
20
star
38

educational-sensational-inspirational-foundational

A website dedicated to a history of foundational web development blog posts.
CSS
20
star
39

heading-anchors

Adds and positions sibling anchor links for heading elements (h1–h6) when they have an `id` attribute.
JavaScript
20
star
40

throbber

A loading indicator overlay for images (and maybe other things later).
JavaScript
15
star
41

artificial-chart

An SVG charting library based on D3.js
JavaScript
15
star
42

gruntlerplate

A default grunt configuration for new projects.
JavaScript
13
star
43

ToolOrDie

A presentation on Web Developer Workflow.
HTML
12
star
44

ALARMd

Web based alarm clock
JavaScript
12
star
45

node-retrieve-globals

Execute a string of JavaScript using Node.js and return the global variable values and functions.
JavaScript
11
star
46

parity-purchasing-power-price

Web Component to show Parity Purchasing Power prices.
JavaScript
11
star
47

font-stats

Generates useful information about a font from a font file.
JavaScript
10
star
48

w3c-banners

A non-image based non-normative proposal for conformance of W3C status banners.
HTML
9
star
49

rainglow

A demo for 11tymeetup.dev
Nunjucks
9
star
50

css-tricks-font-loading

A case study of the font loading for css-tricks.com
HTML
8
star
51

iliveinomaha-banner

Retina friendly progressively enhanced banner for iliveinomaha.com
CSS
7
star
52

foitfout

A web font loading demo to showcase FOIT and FOUT behavior side by side.
JavaScript
6
star
53

async-css-loading

Test cases for asynchronous css loading
HTML
6
star
54

JsTestDriver-Boilerplate

Easy boilerplate for test driven JavaScript projects using the JsTestDriver tool.
Shell
6
star
55

Compatibility-Tests

HTML5 tests used for research for blog posts
5
star
56

BUSYNESS

This project is retired.
JavaScript
5
star
57

uniclode

Another Eleventy Serverless demo, select characters to form a Unicode Range
JavaScript
5
star
58

Raging-Netflix-Queue

RETIRED—A Google Chrome extension, provides a single click add to your Netflix queue while browsing the web.
JavaScript
5
star
59

fundraising-status

Web component to show the current status of a fundraiser.
HTML
4
star
60

a-single-html-file

I am a single HTML file.
HTML
4
star
61

noop

A minimal module to test importing in other tools.
JavaScript
4
star
62

a11y-tests

A series of small atomic tests used to compare accessibility linting tools.
HTML
4
star
63

eleventy-components

4
star
64

unicode-range-interchange

Do math on Unicode Ranges for web fonts.
JavaScript
4
star
65

twitter-avatar-url

Find a twitter avatar image url from a twitter username.
JavaScript
4
star
66

demo-cloudcannon-image-optimization

JavaScript
4
star
67

netlify-kasa-build-status

A little script to update my lights with the status of a Netlify build
JavaScript
3
star
68

browser-logo-icon-set

A multi-color vector icon set (grunticon generated) of browser logos
HTML
3
star
69

DOM-Sailbloat

Find the bloat in your document using this Firebug Lite plugin.
JavaScript
3
star
70

rawhyde

A boilerplate for the Jekyll/Grunt/Buttsweater combination used on zachleat.com and nebraskajs.com.
JavaScript
3
star
71

Firebug-Code-Coverage

Retired source code for an old JavaScript Code Coverage plugin for Firebug.
JavaScript
3
star
72

tweetback-zachleat

HTML
3
star
73

Snapper

JavaScript
2
star
74

demo-eleventy-base-blog

Just testing GitHub templates
HTML
2
star
75

myspacebook

It’s out of this world.
JavaScript
2
star
76

Parlour

A full screen photo gallery with flickr integration.
JavaScript
2
star
77

package-zachleat

Meta package for Zach Leatherman
JavaScript
2
star
78

eleventy-sample-css-manager

Sample created for https://twitter.com/jaffathecake/status/1153759414765203463
JavaScript
2
star
79

gif-party

JavaScript
1
star
80

edge-redirects-test

HTML
1
star
81

zachleat

I AM A ✨ SPECIAL ✨ REPOSITORY
1
star
82

space-jam

HTML
1
star
83

reverse-proxy-test

HTML
1
star