使用 navigator.storage.getDirectory() 访问 Origin Private File System,
把腾讯体字体文件(woff2)以 key-font-tencent 为键持久化到浏览器私有文件系统,
二次进入时直接本地读取,零网络请求。
腾讯体 · 中文渲染效果
落霞与孤鹜齐飞,秋水共长天一色。
0123456789 · Hello, OPFS!
落霞与孤鹜齐飞,秋水共长天一色。
落霞与孤鹜齐飞,秋水共长天一色。
提示:OPFS 与 fetch 均要求安全上下文,请通过 http://localhost 或 https 访问本页面,
file:// 直接打开会失败。
// ① 打开浏览器私有文件系统(OPFS)根目录 const root = await navigator.storage.getDirectory(); const KEY = 'key-font-tencent'; // ② 读取:不传 create,文件不存在时会抛 NotFoundError let file; try { const handle = await root.getFileHandle(KEY); file = await handle.getFile(); // 二次进入:零网络请求 } catch { // ③ 写入:响应流管道直连落盘,大字体文件不会整体驻留内存 const res = await fetch('./assets/tencent.woff2'); const handle = await root.getFileHandle(KEY, { create: true }); await res.body.pipeTo(await handle.createWritable()); file = await handle.getFile(); } // ④ 注册为自定义字体,之后即可用 font-family: Tencent const face = new FontFace('Tencent', await file.arrayBuffer()); document.fonts.add(await face.load());
getFileHandle(name) 不传 create 即为“存在性检测”,靠 NotFoundError 分支决定是否下载。FileSystemFileHandle,getFile() 拿到标准 File,可直接喂给 FontFace。createWritable() 得到 FileSystemWritableFileStream,属于 WritableStream,所以能用 pipeTo;需要下载进度时改为手动 reader.read() + write()(本页做法)。await root.removeEntry(KEY);OPFS 只能在安全上下文(https 或 localhost)中使用。