Skip to content

fontLoadObserver

Mike Byrne edited this page Jan 25, 2022 · 3 revisions

description

Adds a class and to the document and writes a cookie when fonts have loaded. Your project maybe using something like Typekit that comes with its own font observers.

requires

  • fontfaceonload v1.0.2 (handled automatically)
  • cookieHandler (handled automatically)
  • triggerCustomEvent (handled automatically)

parameters

  • fonts array, detailing fonts - see example usage

returns

  • nothing

example usage:

document.addEventListener('DOMContentLoaded', function(){
  fontLoadObserver({
    name: "caslon",
    variants: [
      {
        name: "adobe-caslon-pro",
        weight: "500"
      },
      {
        name: "adobe-caslon-pro",
        weight: "600"
      }
    ]
  });
});
// will add "s-caslon-loaded" to the HTML class list when the fonts loaded
// and write a "A17_fonts_cookie_caslon" cookie
document.addEventListener('DOMContentLoaded', function(){
  fontLoadObserver({
    name: "interstate",
    variants: [
      {
        name: "Interstate"
      },
      {
        name: "Interstate Light"
      }
    ]
  });
});
// will add "s-interstate-loaded" to the HTML class list when the fonts loaded
// and write a "A17_fonts_cookie_interstate" cookie

You'll also want to check for this cookie with your app to stop the fonts flashing if the fonts have likely already loaded. In RoR:

<html class="<% if cookies[:A17_fonts_cookie_caslon] %> s-caslon-loaded<% end %>">

In PHP:

<html class="<?php if (isset($_COOKIE['A17_fonts_cookie_neuzeit'])) { ?> s-caslon-loaded<?php } ?>">

And you'll want to set your CSS up to switch fonts when the web fonts have loaded:

body {
  font-family: Georgia, serif;
  font-size: 16px;
  line-height: 25px;
  font-weight: normal;
}

.s-caslon-loaded body {
  font-family: Caslon, Georgia, serif;
}

This way the page loads, is readable and usable and then when the fonts load - looks as the designers intended