マスタリングWebフォントロード戦略:実用的なガイド
Zach Leathermanのフォント読み込み戦略に関する包括的なガイドは、Web開発者にとって貴重なリソースです。ただし、オプションの数は圧倒的です。この記事では、実用性と実行に焦点を当てて、最良のアプローチを簡素化します。
重要な戦略:
Leatherman Champions 2つの主要な戦略:
これらを掘り下げる前に、用語を明確にしましょう。
フォントホスティングオプション:
クラウドプロバイダー(たとえば、Googleフォント、Adobeフォント):一般的に実装が簡単ですが、ブロッキング動作のためにパフォーマンスが低いことがよくあります。 Google Fonts ' display=swap
パラメーターは、FOUTを有効にすることでわずかな改善を提供します。
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
自己ホスティング:フォントライセンスが必要であり、 @font-face
を使用し、潜在的にfont-display: swap
使用します。これにより、より強力な制御と最適化が可能になります。
自己ホストされたフォントと実装:
@font-face
使用すると、cssのフォント宣言が許可されています。
@font-face { フォントファミリー:ラト; src:url( 'path-to-lato.woff2')形式( 'woff2')、 url( 'path-to-lato.woff')format( 'woff'); / * ...その他のウェイトとスタイル... */ } html { フォントファミリー:lato、sans-serif; }
font-display: swap
自己ホストフォントのFOUTをトリガーします。
クラスを使用したFOUT(クラウドと自己ホストの両方のフォントの両方):
この戦略では、JavaScriptを使用してフォントを非同期にロードし、塗り直しをグループ化し、ユーザーの好みに適応します。また、ユーザーがすでにフォントをインストールしている場合、フォントの読み込みをスキップすることもできます。
フォントを正常にロードします(経由<link>
クラウドホストまたは@font-face
の場合は、自己ホスト用)。
cssフォントロードAPI(またはより広い互換性のためにfontfaceobserver)を使用してください<script> tag:</script>
if ('fonts' in document) { Promise.all([ document.fonts.load('1em Lato'), // ... other weights and styles ... ]).then(_ => { document.documentElement.classList.add('fonts-loaded'); }); }
Use CSS to style the text:
body { font-family: sans-serif; /* System font */ } .fonts-loaded body { font-family: Lato, sans-serif; /* Web font */ }
Optimize for repeat visits using sessionStorage
:
if (sessionStorage.fontsLoaded) { document.documentElement.classList.add('fonts-loaded'); } else { // ... font loading code ... }
FOFT (Flash of Faux Text):
This advanced technique loads the Roman font first, then other styles. "Critical FOFT" optimizes this by loading only essential characters initially. While offering performance gains, it's more complex to implement.
Choosing the Right Strategy:
font-display: swap
if provided by the host; otherwise, use FOUT with Class.@font-face
font-display: swap
is the easiest approach, especially for a small number of font files.This streamlined guide provides a clear path to choosing and implementing the optimal font loading strategy for your project. Remember to prioritize a JavaScript-free approach when feasible, particularly with limited font files.
以上が最適なフォントロード戦略とそれらを実行する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。