- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
import { fontList } from "../cache.js";
import { isDataUrl } from "../../utils/string.js";
/**
* parse/preload a font face
* @param {loader.Asset} data - asset data
* @param {Function} [onload] - function to be called when the asset is loaded
* @param {Function} [onerror] - function to be called in case of error
* @returns {number} the amount of corresponding resource parsed/preloaded
* @ignore
* @example
* preloadFontFace(
* name: "'kenpixel'", type: "fontface", src: "url('data/font/kenvector_future.woff2')"
* ]);
*/
export function preloadFontFace(data, onload, onerror) {
const fontFaceSet = typeof globalThis.document !== "undefined" ? globalThis.document.fonts : undefined;
if (isDataUrl(data.src) === true) {
// make sure it in the `url(data:[<mediatype>][;base64],<data>)` format as expected by FontFace
if (!data.src.startsWith("url(")) {
data.src = "url(" + data.src + ")";
}
}
if (typeof fontFaceSet !== "undefined") {
// create a new font face
let font = new FontFace(data.name, data.src);
// loading promise
font.load().then(() => {
// add the font to the cache
fontList[data.name] = font;
// add the font to the document
fontFaceSet.add(font);
// onloaded callback
if (typeof onload === "function") {
onload();
}
}, () => {
// rejected
if (typeof onerror === "function") {
onerror(data.name);
}
});
} else {
if (typeof onerror === "function") {
onerror(error);
}
}
return 1;
}