Posted about 4 years ago. Visible to the public. Linked content.

Detecting when fonts are loaded via JavaScript

Webfonts are not always available when your JavaScript runs on first page load. Since fonts may affect element sizes, you may want to know when fonts have been loaded to trigger some kind of recalculation.

Vanilla JavaScript / Modern DOM API

In modern browsers (all but IE and Edge) you can use document.fonts. Use load to request a font and receive a Promise that will be resolved once the font is available. Example:

Copy
document.fonts.load('1rem "Open Sans"').then(() => { ... })

jQuery / fontSpy

If your project uses jQuery, you could also use jQuery-FontSpy which also works in IE because it determines the font being loaded by watching for an element's dimensions to change. Example usage:

Copy
fontSpy('Open Sans', { success: function() { alert('Font has been loaded'); }, failure: function() { alert('Font failed to load'); } });

You could also implement something like jQuery-FontSpy in vanilla JS or maybe use vanilla-fontSpy (we have not used it ourselves).

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
12 days ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more