Read more

Detecting when fonts are loaded via JavaScript

Arne Hartherz
March 10, 2015Software engineer at makandra GmbH

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

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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

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

jQuery / fontSpy

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

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 Show archive.org snapshot (we have not used it ourselves).

Posted by Arne Hartherz to makandra dev (2015-03-10 15:56)