此文系讀 font-display 後感,原發在 issues blog 裏面。css
瀏覽器加載字體完成以前,文本默認是不顯示的,這種狀況一般叫作 FOIT。這種方案的好處是不會經歷一個 fallback 字體 -> 指定字體的一個跳轉,缺點是在網絡差的狀況下會有一段時間的空白。默認狀況下大多數瀏覽器會等 3 秒鐘,若是 3 秒鐘以後仍是渲染不出來就轉而選擇 fallback 字體,其中 safari 可能會等得更久,在沒有網絡的狀況下,文本壓根就不渲染了(由於字體加載不出來)。具體瀏覽器是怎麼弄的,參考 Differences in Font Rendering Todaygit
先爲相應的元素設置字體:github
p { font-family: "Arial", "Helvetica", sans-serif; } .font-loaded p { font-family: "Open Sans Regular"; }
而後用 fontfaceobserver 監聽字體加載,在加載完成的時候能夠爲相應的元素添加 class:web
const font = new FontFaceObserver('Open Sans Regular'); const p = document.querySelector('p') font.load().then(function () { p.classList.add('font-loaded') })
@font-face { font-family: "Open Sans Regular"; font-weight: 400; font-style: normal; src: url("fonts/OpenSans-Regular-BasicLatin.woff2") format("woff2"); font-display: swap; }
auto: The default value. The typical browser font loading behavior will take place, which is to hide typefaces that use custom fonts, and then display the affected text when fonts finish loading.promise
swap: The fallback text is shown immediately until the custom font loads. In most cases, this is what we're after. JavaScript-driven font loading solutions almost always aim to emulate this setting.瀏覽器
fallback: This is sort of a compromise between auto and swap. There will be a short period of time (100ms according to Google) that text styled with custom fonts will be invisible. The unstyled text will then appear (if the custom font hasn't already loaded by this point.) Once the font loads, the text is styled appropriately.網絡
optional: Operates exactly like fallback in that the affected text will initially be invisible for a short period of time, and then transition to a fallback font. The similarities end there, though. The optional setting gives the browser freedom to decide whether or not a font should even be used, and this behavior hinges on the user's connection speed. On slow connections, you can expect that custom fonts may not load at all if this setting is used.app