← 中文资源

简体中文版本

用 fonts.ready 等待字体就绪

document.fonts 提供字体加载的就绪面:fonts.ready 等待初始字体完成,fonts.load 精确加载指定字重,fonts.check 同步探测可用性。

阅读英文原文

实现说明

底层就是函数 prepareCatalogFonts。 await 标出每个异步边界——没有 fire-and-forget。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 每一步打印都带着自己的标签:initial fonts settled、faces loaded:、just loaded:。

常见问题

「用 fonts.ready 等待字体就绪」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

入口签名:async function prepareCatalogFonts()

核心语句

document.fonts.addEventListener('loadingdone', (event) => {
  console.log('just loaded:', event.fontfaces.map((face) => face.family));
});
const faces = await document.fonts.load('600 16px "IBM Plex Sans"', 'Aa 123');
await document.fonts.ready; // resolves when pending document fonts settle
console.log('initial fonts settled');

代码示例

// document.fonts is a FontFaceSet: promise-based readiness for the fonts
// the document uses, plus targeted loads for faces a widget needs first.
async function prepareCatalogFonts(): Promise<void> {
  await document.fonts.ready; // resolves when pending document fonts settle
  console.log('initial fonts settled');

  // load() fetches a specific face before the first paint that needs it
  const faces = await document.fonts.load('600 16px "IBM Plex Sans"', 'Aa 123');
  console.log('faces loaded:', faces.length);

  // loadingdone fires whenever a batch of document font loads finishes
  document.fonts.addEventListener('loadingdone', (event) => {
    console.log('just loaded:', event.fontfaces.map((face) => face.family));
  });

  // check() answers synchronously whether a face is already available,
  // optionally limited to the glyphs of a given text
  console.log('600 face ready:', document.fonts.check('600 16px "IBM Plex Sans"'));
  console.log('cjk glyphs ready:', document.fonts.check('600 16px "IBM Plex Sans"', '目录'));
}