Typekit Best Practices

Question about using Typekit. In the older Roots releases, it was easy enough to just throw the JS for Typekit into main.js and be done with it. Since main.js fired in the header, it would load the Typekit code in the header where it’s supposed to. Now that Sage has main.js in the footer instead, this is not possible. What’s the best way to proceed here to balance speed and performance while preventing the dreaded FOUT?

1 Like

I take a simple approach for the most part - now that Typekit’s default is Async loading, the FOUT is always there. I just use the CSS class:

.wf-loading * {
  // prevent FOUT from typekit
  visibility: hidden;
}

.wf-active * {
  /* styles to use after Typekit is loaded */
}

IMHO, javascript to fix this problem is excessive, unless there’s a genuine need for it. With CSS you can fade text in, or just hide like I have above.

So do you just throw the Typekit code into main.js and let it load from the footer?

I normally place the Typekit calls in templates/head.php just below wp_head(). I’m sure someone somewhere will say there’s a better, more efficient way of doing this, but it’s always worked well for me.

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <?php wp_head(); ?>
  <script src="//use.typekit.net/tk-code-goes-here.js"></script>
  <script>try{Typekit.load({ async: true });}catch(e){}</script>
</head>

1 Like

You can totally just throw script in head.php, there’s really no reason not to. See Scott’s response bellow to this post

Hey… Not sure if this adds any value to the conversation, but I thought I would throw my solution into the mix.

In lib/assets.php (I’m using an ACF custom field to add the TypeKit URL, but otherwise $typekit_url would simply be the URL to your TypeKit kit):

if( get_field('typekit_url', 'option') ) {
  $typekit_url = get_field('typekit_url', 'option');
  wp_enqueue_script( 'typekit', $typekit_url, [], null, false);
}

In lib/extras.php (or wherever you like):

function typekit_inline() {
  // Check the typekit script has been enqueued
  if ( wp_script_is( 'typekit', 'done' ) ) { ?>
    <script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<?php
  }
}
add_action( 'wp_head', __NAMESPACE__ . '\\typekit_inline' );

I’m not promising anything here :smile: - we implemented this a while back, and have used it ever since.

If you do try it - please write back here and let me know if it worked for you.