A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 13KB

4 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. title: Font Loading Revisited with Font Events
  2. url: http://www.filamentgroup.com/lab/font-events.html
  3. hash_url: 1e31deb6dc3b4901dcb305145f336709
  4. <p>Last month <a href="http://www.filamentgroup.com/lab/font-loading.html">we wrote about an approach</a> we’d been using to load web fonts in a more responsible manner than browsers tend to do by default. The purpose of the approach was to avoid a typically undesirable browser behavior we often refer to as the “FOIT” (Flash of Invisible Text), in which a browser hides all text that should be styled with a custom font until that font has finished loading.</p>
  5. <h2>A brief recap on the FOIT</h2>
  6. <p>The <em>FOIT</em> tends to be most problematic in browsers like iOS Safari, which hides text for up to 30 seconds before giving up and rendering it with a default font, but it can also be seen in browsers with shorter hiding durations like Chrome, Firefox, and Opera as well. For example, here’s how our site would load in Chrome on a 3G-ish connection if we were loading fonts in a standard way through CSS <code>@font-face</code>. Note that the page content is available for rendering at around 1.7 seconds in the timeline, yet the text is hidden until fonts have finished loading.</p>
  7. <p><img src="http://www.filamentgroup.com/images/font-loading-blog-post/default-thumb.png" alt="Timeline of our website using standard font loading. On a 3G connection."/></p>
  8. <p class="caption"><small>FIG 1: Timeline of our website using standard custom font loading. On a 3G connection.</small></p>
  9. <p>It's nice that these browsers limit their text hiding to 3 seconds, but even 3 seconds is a long time to wait for content that's already downloaded. After all, the performance community tends to agree that 1 second is a reasonable goal for rendering a usable page on a fast connection, and we tend to shoot for rendering something useful in 2 seconds on slower devices on mobile networks as well. Since a page typically requires text to be usable, FOIT timeouts are a concern across most browsers, not just iOS Safari. But again, that browser's behavior is <em>by far</em> the worst.</p>
  10. <h2>A workable workaround</h2>
  11. <p>Our initial approach to working around the FOIT involved converting font files into Data URIs so that those fonts could be embedded directly into font-face definitions in a CSS file. By loading that CSS file in an asynchronous manner (using <a href="https://github.com/filamentgroup/loadCSS">a bit of JavaScript</a>), we could ensure that a browser would immediately render the text in the page using fallback fonts, and the custom fonts would apply once the CSS finished loading.</p>
  12. <h3>An unexpected side effect</h3>
  13. <p>That approach seemed to serve us well, but we recently started noticing that sites using this particular approach sometimes exhibited a small side effect: a brief FOIT or blink that happens long <em>after</em> the fonts finish loading, just before they are applied to the page. It didn’t seem to happen all the time, but we’d been seeing it crop up more and more regularly. The page loading timeline below of our site accessed over a fast connection while using this approach displays this peculiar blip.</p>
  14. <p><img src="http://www.filamentgroup.com/images/font-loading-2/datauri-blip.png" alt="Timeline of our website using data uri font loading"/></p>
  15. <p class="caption"><small>FIG 2: Timeline of our website using async-loaded data URI fonts.</small></p>
  16. <p>In this timeline, the page is usable (with fallback fonts) at around 600ms, but then for about 100ms, a FOIT occurs before the page ultimately returns to a usable state at 800ms. Looking at the request timing, we could see that the FOIT began just after the fonts finished loading. Of course, 800ms is a very fast page load, and a 100ms blink may not be the end of the world, but we found that the problem tended to display more prominently on slower connections and devices and on other sites as well. For example, here's the same load on 3G:</p>
  17. <p><img src="http://www.filamentgroup.com/images/font-loading-2/datauri-3G-blip.png" alt="Timeline of our website using data uri font loading. 3G connection."/></p>
  18. <p class="caption"><small>FIG 3: Timeline of our website using async-loaded data URI fonts. 3G connection.</small></p>
  19. <p>Okay, okay. So another 100ms of hidden text still isn't terrible, but it was certainly <em>odd</em>. And we sometimes saw longer delays of 500ms or so on client sites that were utilizing more custom fonts than our site does.</p>
  20. <p>Something was up, and it seemed we had a little more work to do.</p>
  21. <h2>Finding the source of the problem</h2>
  22. <p>At first we wondered if the blink was just an artifact of repainting/reflowing a moderately complex layout. But the characteristic hidden text alongside visible graphic elements sure looked like your run-of-the-mill FOIT, and sure enough, it was. In short, a FOIT happens when a browser attempts to style an HTML element with a font-family that is defined (via a <code>@font-face</code> declaration) but not yet loaded. Interestingly enough, in this case it appeared that although the CSS and its included fonts had indeed already been delivered over the network to the browser, the browser still seemed to hide the text while parsing the data URI string, which we know can take a little time, particularly on slower devices.</p>
  23. <h2>Enabling fonts when they’re really loaded</h2>
  24. <p>After realizing that even data URIs can introduce a FOIT while they’re being parsed, we wanted to ensure that we applied our fonts to the page only after they were truly ready to render. Fortunately, Zach here had recently written <a href="https://dev.opera.com/articles/better-font-face/">a great article over at Dev.Opera about an upcoming font events API</a> that is designed for this specific purpose, and there are some nice lightweight polyfills available (<a href="https://github.com/zachleat/fontfaceonload">1</a>, <a href="https://github.com/bramstein/fontfaceobserver">2</a>) to start experimenting with it today. To experiment with a font events approach, we gave <a href="https://github.com/bramstein/fontfaceobserver">Bram Stein’s FontFaceObserver script</a> a try.</p>
  25. <p>Here’s how it looks to use <code>fontfaceobserver</code> to set up a loading listener for one of the fonts used on this site (Open Sans Pro):</p>
  26. <pre><code>new w.FontFaceObserver( "Source Sans Pro" )
  27. .check()
  28. .then( function(){ console.log( “Loaded!” ); });
  29. </code></pre>
  30. <p>You can read more about how to use Bram’s script on Github, but in short, you can specify a font family and other identifying details such as the font's weight and style. Once the observer is created, you just need to <code>check()</code> it, and then get a callback when it finishes loading (which is easy to do through the <code>then()</code> method). Neat!</p>
  31. <p>With this tool in hand, we followed a clever idea from Zach’s Opera article to qualify the use of our fonts throughout the site through a class selector, which we could add once the fonts were loaded. For example, the <code>body</code> element would reference a fallback <code>sans-serif</code> font until a class of <code>fonts-loaded</code> was present on the <code>html</code> element:</p>
  32. <pre><code>body {
  33. font-family: sans-serif;
  34. }
  35. .fonts-loaded body {
  36. font-family: Source Sans Pro, sans-serif;
  37. }
  38. </code></pre>
  39. <p>And our font observer callback can add that class when the font loads!</p>
  40. <pre><code>new w.FontFaceObserver( "Source Sans Pro" )
  41. .check()
  42. .then( function(){
  43. w.document.documentElement.className += " fonts-loaded";
  44. });
  45. </code></pre>
  46. <p>With that logic in place, our data URI fonts layered in without a blink. Great!</p>
  47. <p><img src="http://www.filamentgroup.com/images/font-loading-2/datafontevents.png" alt="Timeline of our website using async-loaded data URI fonts with font events. No FOIT!"/></p>
  48. <p class="caption"><small>FIG 4: Timeline of our website using async-loaded data URI fonts with font events. No FOIT!</small></p>
  49. <h2>Great. So why the URIs?</h2>
  50. <p>At this point, we had a fix, but it got us thinking that maybe we didn’t need to go through the whole data URI route anymore, now that we were using a font events polyfill anyway. After all, these new font loading and listening tools are designed to help load fonts referenced via regular old CSS <code>@font-face</code> declarations, and who knows, maybe that’d be simpler and faster as well.</p>
  51. <p>To make the switch, we removed the CSS file containing our data URIs, and the JavaScript logic we had used to load that CSS, and placed standard <code>@font face</code> rules referencing Woff2, Woff, and TTF files in our CSS, like this:</p>
  52. <pre><code>@font-face {
  53. font-family: 'Source Sans Pro';
  54. src: url('/css/type/sourcesanspro-light-webfont.woff2') format('woff2'),
  55. url('/css/type/sourcesanspro-light-webfont.woff') format('woff'),
  56. url('/css/type/sourcesanspro-light-webfont.ttf') format('truetype');
  57. font-weight: 300;
  58. font-style: normal;
  59. }
  60. body {
  61. font-family: sans-serif;
  62. }
  63. .fonts-loaded body {
  64. font-family: Source Sans Pro, sans-serif;
  65. }
  66. </code></pre>
  67. <p>Conveniently, the FontFaceObserver script will actually load a font for you when you call it, as long as the font you’re observing is referenced in a <code>@font-face</code> declaration in the CSS. It does this by generating an HTML element and styling it with the font you’re referencing, which causes the browser to kick off a request to its format of choice.</p>
  68. <h2>The Result: Faster than ever!</h2>
  69. <p>By referencing our fonts using CSS <code>@font-face</code> and using font loading APIs to load and enable them when ready, we’ve found our fastest page load yet (complete in 600 milliseconds on wifi!) while retaining the progressive font rendering we desired.</p>
  70. <p>Here’s a timeline of our homepage now, loaded over a wifi connection.</p>
  71. <p><img src="http://www.filamentgroup.com/images/font-loading-2/fontevents-final.png" alt="Timeline of our website using `@font-face` and font events. On a wifi connection."/></p>
  72. <p class="caption"><small>FIG 5: Timeline of our website using `@font-face` and font events. On a wifi connection.</small></p>
  73. <h3>Last step: Optimizing return visits</h3>
  74. <p>For return visits, we wanted to see if we could enable the font as soon as possible, knowing that it'd likely be cached in the browser from a prior load. To do this, we simply set a cookie after the fonts finish loading on the first visit. Next page view, the server side checks for that cookie and sets the <code>fonts-loaded</code> class in the HTML source that's delivered to the browser. Using SSI for example, that looks like this:</p>
  75. <pre><code>
  76. &lt;!--#if expr="$HTTP_COOKIE=/fonts\-loaded\=true/" --&gt;
  77. &lt;html lang="en" class="fonts-loaded"&gt;
  78. &lt;!--#else --&gt;
  79. &lt;html lang="en"&gt;
  80. &lt;!--#endif --&gt;
  81. </code></pre>
  82. <p>And with that tweak, our return visits look as fast as can be. We have a complete render at 300ms on a fast connection:</p>
  83. <p><img src="http://www.filamentgroup.com/images/font-loading-2/fontevents-repeat.png" alt="Timeline of our website's return visit timing on wifi."/></p>
  84. <p class="caption"><small>FIG 6: Timeline of our website's return visit timing on wifi.</small></p>
  85. <p>But what's particularly nice about this is that it is able to optimize <em>all</em> further browsing on the site, not just revisiting a page a user has already seen.</p>
  86. <h2>Looking ahead</h2>
  87. <p>By using font events and a clever polyfill, we were able to get our fonts to load progressively, saving our users from the dreaded FOIT. Looking ahead, we may be able to specify that our fonts load this way with a simple <code>font-rendering</code> CSS property instead of having to bother with JavaScript font APIs at all. For example, to specify that fonts should load progressively, as we've designed above, we can simply specify the following in our CSS: <code>font-rendering: swap;</code>. Of course, like any new property, it'll be a while before we can rely on that behavior to work across a broad number of devices. Our biggest worry these days is iOS Safari with its incredibly annoying FOIT delay, so here's hoping Apple gets on board with this new approach in an upcoming version!</p>
  88. <p>For more on how that evolves, we'll keep our eyes on this draft specification: <a href="https://github.com/KenjiBaheux/css-font-rendering">CSS Font Rendering</a>.</p>
  89. <h2>Thanks for reading along!</h2>
  90. <p>If you're interested, we posted an example page on github to show how things are set up.</p>
  91. <ul>
  92. <li><a href="http://master.origin.font-loading.fgtest.com/font-events.html">Font events demo page</a></li>
  93. <li><a href="https://github.com/filamentgroup/font-loading/blob/master/font-events.html">Font events demo page source</a>.</li>
  94. </ul>